Using Swift 3 Stopping a scheduledTimer, Timer continue firing even if timer is nil

后端 未结 4 513
無奈伤痛
無奈伤痛 2021-02-02 07:03

We call startTimer function to start a timer. When we wanted to stop it we call stopTimerTest function but after we called stopTimer function the timerTestAction keeps firing. T

相关标签:
4条回答
  • 2021-02-02 07:17

    Make sure when you call StartTimer it is nil and if you call StartTimer twice without calling StopTimer. You will lose your original pointer and you can't stop it.

     var timer : Timer? = nil {
            willSet {
                timer?.invalidate()
            }
        }
    

    Start and Stop timer like ...

    func startTimer() {
        stopTimer()
        guard self.timer == nil else { return }
        self.timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.fetchData), userInfo: nil, repeats: true)
    }
    
    func stopTimer() {
        guard timer != nil else { return }
        timer?.invalidate()
        timer = nil
    }
    
    0 讨论(0)
  • 2021-02-02 07:22

    Most likely you've called startTimer twice without calling stopTimerTest. If you do that, you'll lose your pointer to the original timer and never be able to invalidate it.

    The typical approach is to manage invalidation as a part of setting:

    var timerTest : Timer? = nil {
        willSet {
            timerTest?.invalidate()
        }
    }
    

    Then stopping is just setting to nil:

    func stopTimerTest() {
        timerTest = nil
    }
    
    0 讨论(0)
  • 2021-02-02 07:24

    Try to make the following changes to your code:

    First, you have to change the way you declare timerTest

    var timerTest : Timer?
    

    then in startTimer before instantiating check if timerTest is nil

    func startTimer () {
      guard timerTest == nil else { return }
    
      timerTest =  Timer.scheduledTimer(
          timeInterval: TimeInterval(0.3),
          target      : self,
          selector    : #selector(ViewController.timerActionTest),
          userInfo    : nil,
          repeats     : true)
    }
    

    Finally in your stopTimerTest you invalidate timerTest if it isn't nil

    func stopTimerTest() {
      timerTest?.invalidate()
      timerTest = nil
    }
    
    0 讨论(0)
  • 2021-02-02 07:31

    Check, are you really call stopTimerTest(), because timerTest.invalidate() is correct for stopping timer.

    func stopTimerTest() {
        print("stopTimer")
        timerTest.invalidate()
    }
    
    0 讨论(0)
提交回复
热议问题