0

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

循环功能:

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

但它不起作用,它仍然调用并且我的应用程序崩溃了。

谁能帮我?提前致谢

4

2 回答 2

0

在我看来,您真正想做的是使用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"];
于 2013-07-03T03:16:26.743 回答
0

[NSThread exit];或者[NSThread performSelector:@selector(exit) onThread:thread withObject:nil waitUntilDone:YES];

于 2021-11-30T03:55:18.333 回答