【问题标题】:Stop NSThread on iOS在 iOS 上停止 NSThread
【发布时间】:2013-07-03 03:03:11
【问题描述】:

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

循环功能:

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

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

谁能帮帮我?提前致谢

【问题讨论】:

  • 您能否添加应用程序崩溃时收到的错误消息以及它在哪一行崩溃?另外scheduledTimerWithTimeInterval... 会在当前线程上安排计时器(这是主线程,因为它是从viewWillAppear 调用的),您不应该在主线程上调用[NSThread sleep...]
  • 因为你的方法没有任何参数,虽然你正在传递它,只需将计时器中的方法名称更改为 (updateArray) 就可以了。

标签: iphone ios objective-c nsthread


【解决方案1】:

在我看来,您真正想做的是在FileSizeArrayFileCurrentSizeArray 更改时使用Key-Value Observing 接收回调。

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

【讨论】:

  • 谢谢,但它不起作用,我想在视图消失时停止 NSThread。
  • 我相当肯定 count 不是 KVO 兼容的属性。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    相关资源
    最近更新 更多