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

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

提交回复
热议问题