2013-07-03 26 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