How to check if a NSTimer is running or not in Swift?

What I do (in both languages) is to make my timer weak. In swift it would be a weak optional.

weak var myTimer: NSTimer?

Then I create a timer with

myTimer = NSTimer.scheduledTimerWithTimeInterval(1,
          target: self,
          selector: "timerFired:",
          userInfo: nil,
          repeats: false)

And then you can use

if timer == nil

to tell if it's running.

To stop the timer you just call

myTimer?.invalidate()

In Objective-C it would be

[myTimer invalidate];

That works in Objective-C because sending messages to nil pointers is valid, and just does nothing.

If you don't want to use a weak optional, you can query a timer to see if it's running by looking at it's valid property.


How about the below option? Can you see if this works for you

if myTimer.valid {
}

Tags:

Ios

Iphone

Swift