2011-03-04 74 views
3
[NSTimer scheduledTimerWithTimeInterval: target: selector: userInfo: repeats:NO]; 

當重複:設置爲NO時,是否需要使指定選擇器內的計時器無效?(iphone)重複時是否需要使計時器無效:否?

謝謝

編輯

另一個問題,如果它的自我無效信號,

你如何正確地取消這種定時器?
由於無效已經失效的計時器會崩潰我承擔?

維護一個指向定時器的指針,並將其設置爲nil在選擇器內部會被觸發?

回答

6

否,計時器會作廢本身

+0

謝謝。然後http://stackoverflow.com/questions/1429571/how-to-stop-nstimer-event這段代碼實際上應該保留定時器來正確取消定時器,我認爲?因爲使自動失效的計時器失效會崩潰? – eugene 2011-03-04 08:28:56

+0

看到我的編輯請 – eugene 2011-03-04 08:32:12

+0

如果它是一個不重複的定時器(重複:否),不需要取消定時器。定時器使自己失效並被釋放。對於重複計時器,您需要維護對計時器的引用以顯式調用invalidate。 – Kai 2011-03-04 08:44:16

0

如果重複是YES,定時器將反覆重新安排自己,直到無效。如果否,計時器在火災後將失效。

1

@Eugene如果您正在使用

[NSTimer scheduledTimerWithTimeInterval: target: selector: userInfo: repeats:YES]; 

然後在選擇方法,你需要給這樣一個

- (void)timerFireMethod:(NSTimer*)theTimer 

功能,所以當你要使它無效,你可以有一個條件像這樣的

if(workDone == YES) 
{ 
    [theTimer invalidate]; 
} 

但如果你是在重複選項可使用NO則計時器會使自己失效。

1

您可以維護標誌以保存定時器是否已被觸發。

例如。

BOOL gameOver = NO; 
    NSTimer * gameOverTimer; 


-(void)startGame 
{ 

    gameOverTimer = [NSTimer scheduledTimerWithTimeInterval:600 target:self selector:@selector(stopLevel:) userInfo:nil repeats:NO]; 
    // your code 
} 

-(void)stopLevel:(id)sender 
{ 
    gameOver = YES; 
    // your code 
} 

-(void)levelFinishedSuccesfully 
{ 
    // this method will get called if user finishes the level before your timer ends/stops the level. So the timer is valid and we need to invalidate it 
    if(!gameOver) 
    { 
      [gameOverTimer invalidate]; 
      gameOverTimer = nil; 
    }  
     // your code 
} 

希望這會有所幫助。

0

你缺少定時器源添加到您runloop

addTimer:forMode:

相關問題