在iOS上停止NSThread

我有函数调用循环,但我想调用它,如果我的视图出现,而不是视图消失时调用它。

循环function:

-(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; 

但它不工作,它仍然打电话,我的应用程序崩溃。

谁能帮我? 提前致谢

在我看来,你真正想要做的就是当FileSizeArrayFileCurrentSizeArray改变时使用Key-Value Observing来接收callback。

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"];