4
[NSTimer scheduledTimerWithTimeInterval: target: selector: userInfo: repeats:NO];

当 repeats: 设置为 NO 时,是否需要使指定选择器内的计时器无效?

谢谢

编辑

另一个问题,如果它自己无效,

您如何正确取消此类计时器?
由于使已经失效的计时器失效我假设会崩溃?

维护一个指向计时器的指针并将其设置为 nil 在将被触发的选择器内?

4

5 回答 5

7

不,计时器会自行失效

于 2011-03-04T08:23:34.663 回答
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
}

希望这可以帮助。

于 2011-03-04T08:47:04.707 回答
1

@Eugene 如果您正在使用

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

然后在选择器方法中,您需要提供这样的功能

- (void)timerFireMethod:(NSTimer*)theTimer

所以当你想让它失效时,你可以有这样的条件

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

但是,如果您NO在重复选项中使用,则计时器将自行失效。

于 2011-03-04T08:43:09.367 回答
0

如果repeats 是YES,定时器将重复重新调度自己直到失效。如果否,定时器将在触发后失效。

于 2011-03-04T08:29:59.650 回答
0

您缺少将计时器源添加到您的运行循环

addTimer:forMode:

于 2014-04-03T22:59:04.233 回答