swift invalidate timer doesn't work

我的未来我决定 提交于 2019-11-29 09:14:19

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!