2013-07-03 28 views
0

我想在查看disapear时停止呼叫循环功能。我怎样才能做到这一点?这是我的代码:如何在IOS中停止呼叫循环功能

-(void) viewWillAppear:(BOOL)animated 
{ 
    [self performSelectorInBackground:@selector(updateArray) withObject:nil]; 

} 

而且:当这个视图中消失

​​

updateArray通常callled。我想停下来调用updateArray功能提前

感谢

+1

你有清除你的问题吗? –

+1

这与你以前的问题有什么不同http://stackoverflow.com/questions/17438987/stop-nsthread-on-ios? –

+0

呃...你可以使用'break'来停止任何循环。 – TheTiger

回答

2

请在viewWillAppear中的BOOL伊娃或财产

BOOL loopShouldRun; 

将其设置为YES

然后使用此代码

-(void)updateArray 
{ 
    while (loopShouldRun) 
    { 
     NSLog(@"IN LOOP"); 
     [NSThread sleepForTimeInterval:2.0]; 
....} 
} 

和viewWillDisappear它设置为NO。

但正如@Michael Deuterman在评论中提到的那样,在sleepTimer激发之前视图消失时可能会出现问题。

所以继承人是NSTimer的另一个解决方案。在viewWillAppear@property (strong) NSTimer *timer;

  • 创建定时器:在viewWillDiappear

    timer = [NSTimer timerWithTimeInterval:2.0 invocation:@selector(updateArray) repeats:Yes]

  • 无效定时器:

    • 创建NSTimer伊娃/ @财产

      if ([self.timer isValid]) { [self.timer invalidate] }

    updateArray现在应该是这样的:

    -(void)updateArray { 
        NSLog(@"in loop"); 
    } 
    
  • +0

    这不是最佳答案。这个@Pfitz的问题在于,“sleepForTimeInterval:2.0'中的长时间睡眠时间返回前,视图可能会消失并释放。 –

    +0

    timer = [NSTimer timerWithTimeInterval:2.0调用:@selector(updateArray)重复:是]它错误。它不起作用 –

    0
    while (1) 
    { 
        NSLog(@"IN LOOP"); 
        [NSThread sleepForTimeInterval:2.0]; 
    } 
    

    而(1)将是真正的永恒。要停止它,你需要有一个条件来阻止循环的发生。

    例如,

    while (1) 
    { 
        NSLog(@"IN LOOP"); 
        [NSThread sleepForTimeInterval:2.0]; 
        if(something happens) 
        break; 
    } 
    

    希望它可以帮助你。

    +0

    或(!(发生的事情)){...} – zbMax

    0

    这是一个简单的逻辑......只取标记变量和更新标志varibale的价值,当你viewdisapper然后

    - (void)viewWillDisappear:(BOOL)animated 
    

    上述方法方法将调用视图中消失之前

    viewDidDisappear:(BOOL)animated

    上面的方法也存在。将被称为刚过你的看法也消失

    所以你可以根据你的标志变量值改变一个以上method.then你的标志变量的值只是把break在while循环,你的循环将打破 。的performSelector

    NSThread *myThread; // preferable to declare in class category in .m file or in .h file 
    

    viewWillAppear中

    myThread = [[NSThread alloc] initWithTarget:self selector:@selector(updateArray) object:nil]; 
    [myThread start]; 
    

    viewWillDisappear

    [myThread cancel]; // This will stop the thread and method will get stopped from execution 
    myThread = nil; // Release and nil object as we are re-initializing in viewWillAppear