在iOS上停止NSThread [英] Stop NSThread on iOS

查看:86
本文介绍了在iOS上停止NSThread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有函数调用循环,但是如果要显示我的视图,我想调用它,而在视图消失时不要调用它.

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

循环功能:

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

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

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

有人可以帮助我吗?预先感谢

Can anyone help me? Thanks in advance

推荐答案

在我看来,您真正想做的是使用

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.

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

这篇关于在iOS上停止NSThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆