30

I have a timer 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. At a certain condition, I want to check if the timer is active then invalidate the timer. My question is how do I find that timer is active or not?

Rahul Vyas
  • 28,260
  • 49
  • 182
  • 256

4 Answers4

70

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)

Kevin
  • 2,810
  • 1
  • 23
  • 19
8

NSTimer has an -isValid method.

Alex Rozanski
  • 37,815
  • 10
  • 68
  • 69
NSResponder
  • 16,861
  • 7
  • 32
  • 46
5

Keep the timer in an instance variable, and set timer = nil when there's no timer running (i.e. after you call [timer invalidate]). Then, to check if the timer is active, you can just check whether timer == nil.

ianh
  • 836
  • 1
  • 5
  • 15
1

In Swift, you can use the isValid boolean to see if the timer is running:

if timer.isValid {
   // Do stuff
}

From the Apple docs:

A Boolean value that indicates whether the receiver is currently valid. (read-only)

true if the receiver is still capable of firing or false if the timer has been invalidated and is no longer capable of firing.

Community
  • 1
  • 1
Crashalot
  • 33,605
  • 61
  • 269
  • 439