Stop NSThread on iOS

眉间皱痕 提交于 2019-12-12 02:27:06

问题


I have function call loop, but I want call it if my view appears, and not call it when the view disappears.

Loop 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];
        ...
}

And in ViewWillAppear()

timer= [NSTimer scheduledTimerWithTimeInterval: 2.0
                                              target: self
                                              selector:@selector(updateArray:)
                                              userInfo: nil repeats:NO];

And in DidDisAppear()

[timer invalidate];
timer = nil;

But it not working, it still call and my app has crash.

Can anyone help me? Thanks in advance


回答1:


It sounds to me that what you really want to do is use Key-Value Observing to receive a callback when FileSizeArray and FileCurrentSizeArray change.

In ViewDidAppear:

[self addObserver:self forKeyPath:@"FileSizeArray.count" options: 0 context: nil];
[self addObserver:self forKeyPath:@"FileCurrentSizeArray.count" options: 0 context: nil];

Callback:

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

}

remember to unregister:

[self removeObserver:self forKeyPath:@"FileSizeArray"];
[self removeObserver:self forKeyPath:@"FileCurrentSizeArray"];


来源:https://stackoverflow.com/questions/17438987/stop-nsthread-on-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!