[NSTimer scheduledTimerWithTimeInterval: target: selector: userInfo: repeats:NO];
当重复:设置为NO时,是否需要使指定选择器内的计时器无效?(iphone)重复时是否需要使计时器无效:否?
谢谢
编辑
另一个问题,如果它的自我无效信号,
你如何正确地取消这种定时器?
由于无效已经失效的计时器会崩溃我承担?
维护一个指向定时器的指针,并将其设置为nil在选择器内部会被触发?
[NSTimer scheduledTimerWithTimeInterval: target: selector: userInfo: repeats:NO];
当重复:设置为NO时,是否需要使指定选择器内的计时器无效?(iphone)重复时是否需要使计时器无效:否?
谢谢
编辑
另一个问题,如果它的自我无效信号,
你如何正确地取消这种定时器?
由于无效已经失效的计时器会崩溃我承担?
维护一个指向定时器的指针,并将其设置为nil在选择器内部会被触发?
否,计时器会作废本身
如果重复是YES,定时器将反复重新安排自己,直到无效。如果否,计时器在火灾后将失效。
@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:
谢谢。然后http://stackoverflow.com/questions/1429571/how-to-stop-nstimer-event这段代码实际上应该保留定时器来正确取消定时器,我认为?因为使自动失效的计时器失效会崩溃? – eugene 2011-03-04 08:28:56
看到我的编辑请 – eugene 2011-03-04 08:32:12
如果它是一个不重复的定时器(重复:否),不需要取消定时器。定时器使自己失效并被释放。对于重复计时器,您需要维护对计时器的引用以显式调用invalidate。 – Kai 2011-03-04 08:44:16