[英](iphone) do I need to invalidate timer when repeats: no?
[NSTimer scheduledTimerWithTimeInterval: target: selector: userInfo: repeats:NO];
當重復:設置為NO時,是否需要使指定選擇器內的計時器無效?
謝謝
編輯
另一個問題,如果它自我失效,
你如何正確取消這樣的計時器?
由於無效已經失效的計時器會崩潰我假設?
維護一個指向計時器的指針,並將其設置為將被觸發的選擇器內的nil?
不,計時器將使自身無效
@Eugene如果你正在使用
[NSTimer scheduledTimerWithTimeInterval: target: selector: userInfo: repeats:YES];
那么在選擇器方法中你需要給出一個像這樣的函數
- (void)timerFireMethod:(NSTimer*)theTimer
所以當你想讓它失效時,你就可以得到像這樣的條件
if(workDone == YES)
{
[theTimer invalidate];
}
但是如果你在重復選項中使用NO
,則計時器將使自身無效。
您可以保持標志以保存定時器是否已被觸發。
例如。
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
}
希望這可以幫助。
你缺少將計時器源添加到你的runloop
addTimer:forMode:
如果重復為是,則計時器將反復重新安排自己,直到無效。 如果為NO,計時器將在其觸發后失效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.