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

后端 未结 4 596
無奈伤痛
無奈伤痛 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
    }
    

提交回复
热议问题