swift invalidate timer doesn't work

前端 未结 3 1399
庸人自扰
庸人自扰 2020-12-11 00:42

I have this problem for a few days now and I don\'t get what I am doing wrong.

My application is basically just creating some timers. I need to stop them and create

3条回答
  •  旧时难觅i
    2020-12-11 00:49

    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).

提交回复
热议问题