Using Swift 3 Stopping a scheduledTimer, Timer con

2019-03-14 13:34发布

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. To check the timer condition we used print and print in timerActionTest returns nil.

var timerTest: Timer? = nil

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

func timerActionTest() {
    print(" timer condition \(timerTest)")
}

func stopTimerTest() {
    timerTest.invalidate()
    timerTest = nil
}

标签: timer swift3
3条回答
趁早两清
2楼-- · 2019-03-14 13:56

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
}
查看更多
做自己的国王
3楼-- · 2019-03-14 14:06

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

func stopTimerTest() {
    print("stopTimer")
    timerTest.invalidate()
}
查看更多
Ridiculous、
4楼-- · 2019-03-14 14:11

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 () {

  if timerTest == nil {
    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() {
 if timerTest != nil {
    timerTest!.invalidate()
    timerTest = nil
 }
}
查看更多
登录 后发表回答