swift invalidate timer doesn't work

The usual way to start and stop a timer safely is

var timer : NSTimer?

func startTimer()
{
  if timer == nil {
    timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: "timerFired", userInfo: nil, repeats: true)
  }
}

func stopTimer()
{
  if timer != nil {
    timer!.invalidate()
    timer = nil
  }
}

startTimer() starts the timer only if it's nil and stopTimer() stops it only if it's not nil.

You have only to take care of stopping the timer before creating/starting a new one.

In Swift 3 replace

  • NSTimer with Timer,
  • NSTimer.scheduledTimerWithTimeInterval( with Timer.scheduledTimer(timeInterval:
  • selector: "timerFired" with selector: #selector(timerFired).

Make sure you're calling invalidate on the same thread as the timer.

From the documentation:

Special Considerations You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.

https://developer.apple.com/documentation/foundation/nstimer/1415405-invalidate?language=objc

Tags:

Ios

Swift

Nstimer