How to find if NSTimer is active or not?

Rahul Vyas picture Rahul Vyas · Oct 28, 2009 · Viewed 23.6k times · Source

I have a something like this:

 NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                   target:self
                                                 selector:@selector(updateCountdown)
                                                 userInfo:nil
                                                  repeats:YES]; 

I am updating a label's text using this timer. Not at a certain condition I want to check if timer is active then invalidate the timer. My question is how do I find that timer is active or not?

Answer

Kevin picture Kevin · Oct 28, 2009

When a non repeating timer fires it marks itself as invalid so you can check whether it is still valid before cancelling it (and of course then ridding yourself of it).

if ( [timer isValid] && yourOtherCondition){
    [timer invalidate], timer=nil;
}

In your case you have a repeating timer so it will always be valid until you take some action to invalidate it. Looks like in this case you are running a countdown so it will be up to you to make sure you invalidate and rid yourself of it when the countdown reaches the desired value (In your updateCountdown method)