在iOS上停止NSThread
问题描述:
我有函数调用循环,但是我想在我的视图出现时调用它,并且在视图消失时不要调用它。在iOS上停止NSThread
循环功能:
-(void)updateArray
{
while (1)
{
NSLog(@"IN LOOP");
[NSThread sleepForTimeInterval:2.0];
if([FileSizeArray count] >0 || [FileCurrentSizeArray count] >0)
{
[FileSizeArray removeObjectsInRange:NSMakeRange(1, FileSizeArray.count-1)];
[FileCurrentSizeArray removeObjectsInRange:NSMakeRange(1, FileSizeArray.count-1)];
}
[FileNameArray removeAllObjects];
[UserNameArray removeAllObjects];
...
}
而且在ViewWillAppear()
timer= [NSTimer scheduledTimerWithTimeInterval: 2.0
target: self
selector:@selector(updateArray:)
userInfo: nil repeats:NO];
而且在DidDisAppear()
[timer invalidate];
timer = nil;
但它不能正常工作,但它仍然呼吁和我的应用程序已经崩溃。
任何人都可以帮助我吗?在此先感谢
答
在我听起来,你真的想要做的是使用Key-Value Observing接收回拨时FileSizeArray
和FileCurrentSizeArray
更改。
在ViewDidAppear
:
[self addObserver:self forKeyPath:@"FileSizeArray.count" options: 0 context: nil];
[self addObserver:self forKeyPath:@"FileCurrentSizeArray.count" options: 0 context: nil];
回调:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"FileSizeArray.count"]) {
//do something
} else if ([keyPath isEqualToString:@"FileCurrentSizeArray.count"]) {
//do something
}
}
记得注销:
[self removeObserver:self forKeyPath:@"FileSizeArray"];
[self removeObserver:self forKeyPath:@"FileCurrentSizeArray"];
+0
谢谢,但它不工作,我想在视图消失时停止NSThread。 –
+0
我很确定'count'不是符合KVO的属性。 –
你可以添加,当应用程序崩溃您收到并在其行吧错误信息坠毁?另外'scheduledTimerWithTimeInterval ...'在当前线程(这是主要线程,因为它从'viewWillAppear'调用)调度定时器,并且你不应该在主线程上调用'[NSThread sleep ...]'。 –
,因为你的方法没有任何参数,虽然你传递它,只要将方法名称改为(updateArray)就可以了。 –