2016-06-09 24 views
-1

我在我的一個viewControllers中有一個函數,每10秒執行一次。IOS - Objective C - 如何在退出視圖時停止執行週期性功能?

我希望此功能在我退出視圖時停止它的執行。

我想這和平的代碼:

-(void)viewWillDisappear:(BOOL)animated 
{ 
    NSError *error2; 
    if ([_managedObjectContext save:&error2] == NO) { 
     NSAssert(NO, @"Save should not fail\n%@", [error2 localizedDescription]); 
     abort(); 
    } 
    else 
     NSLog(@"Context Saved"); 



    [self stopTimer]; 
    NSLog(@"View will disappear now"); 
} 

據basicly調用方法stopTimer會給null值的計時器。

- (void) stopTimer 
{ 
    [timer invalidate]; 
    timer = nil; 
} 

我的問題是即使我離開我的視圖,我的函數仍然執行。並永不停止。我怎樣才能解決這個問題?

編輯:

這是我的NSTimer調用的函數:

- (void) MyFunctionCalledByNSTimer 
{ 
    [timer invalidate]; 
    timer = [NSTimer scheduledTimerWithTimeInterval:10.0f 
            target:self selector:@selector(Function1) userInfo:nil repeats:YES]; 

} 

我宣佈我的NSTimer在我的viewController

NSTimer *timer; 

的.M如果您需要更多撕成小塊的代碼只是問,我會編輯問題。

+0

'1)'您的'viewWillDisappear:'不會編譯,因爲它缺少'}' - 請添加完整,正確的方法。 '2)'你不是在調用'[super viewWillDisappear:animated];' - 請將其添加到你的方法中。 '3)'請添加由計時器調用的函數,該函數經常運行到該問題。 '4)'請添加聲明定時器的代碼以及它將運行的方法。 –

+1

請問您可以添加創建nstimer的代碼或創建nstimer的代碼? –

+0

@RoboticCat我們不需要調用super viewWillDisappear,除非我們想重寫它。即使我們沒有調用super,該方法也會被調用! –

回答

0

使用此代碼 通話stopTimer在主線程

-(void)viewWillDisappear:(BOOL)animated 
{ 
    NSError *error2; 
    if ([_managedObjectContext save:&error2] == NO) { 
     NSAssert(NO, @"Save should not fail\n%@", [error2 localizedDescription]); 
     abort(); 
    } 
    else 
     NSLog(@"Context Saved"); 


    dispatch_async(dispatch_get_main_queue(), ^{ 
    //Your main thread code goes in here 
    [self stopTimer];  
    }); 


    NSLog(@"View will disappear now"); 
} 

記住,你必須在其上安裝了定時器線程發送無效消息。如果您從另一個線程發送此消息,則與定時器關聯的輸入源可能不會從其運行循環中刪除,這可能會阻止線程正常退出。

+0

我剛剛試過你的代碼,它不適用於我,因爲即使我退出了它的視圖,該函數仍在執行。你認爲在viewWillDisappear中調用stoptimer方法是正確的嗎?因爲我在一些類似於我的人的問題中看到一個類似於我的人叫停止者在viewDidDisappear – samouray

+0

我們也可以從以前的viewcontroller viewwillappper方法發出通知 – suthar

+0

還檢查您的計時器是否有內存 – suthar

3

可能會因爲創建多個計時器而發生問題,並且僅使您參考的內容失效。

因此,可修改MyFunctionCalledByNSTimer像下面將解決您的問題:

- (void) MyFunctionCalledByNSTimer 
{ 
    if(!timer){ 

      timer = [NSTimer scheduledTimerWithTimeInterval:10.0f 
            target:self selector:@selector(Function1) userInfo:nil repeats:YES]; 
    } 

} 

現在,只有一個計時器參考將在那裏和[timer invalidate]會作廢計時器。

+0

這是正確答案,我非常感謝你 – samouray

+0

歡迎你:) @ samouray –

+0

你好,我很抱歉,但我只是意識到,我的功能仍然執行後,即使我實施此解決方案。 我現在很困惑,昨天它似乎在工作,現在不是。我希望你能幫助我,如果你想了解我的代碼的更多信息。 – samouray