开发者

(iphone) do I need to invalidate timer when repeats: no?

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

When repeats: is set to NO, do I need to invalidate the timer inside the specified selector?

Thank you

Edit

Another question, if it self invalidates,

开发者_如何学C

How do you properly cancel a such timer?

Since invalidating already-invalidated timer would crash I assume?

maintain a pointer to the timer and set it to nil inside the selector that will get fired?


No, the timer will invalidate itself


@Eugene if you are using

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

then in the selector method you need to give a function like this one

- (void)timerFireMethod:(NSTimer*)theTimer

so when you want to invalidate it you can have a condition like this one

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

But if you are using NO in the repeat option then the timer will invalidate itself.


You can maintain flag to save whether the timer has been fired or not.

eg.

    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
}

Hope this helps.


If repeats is YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.


you are missing to add the timer source to your runloop

addTimer:forMode:

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜