使用Swift 3停止scheduledTimer,即使计时器为零,计时器也会继续启动

使用Swift 3停止scheduledTimer,即使计时器为零,计时器也会继续启动,timer,swift3,Timer,Swift3,我们调用startTimer函数来启动计时器。当我们想要停止它时,我们调用stopTimerTest函数,但在调用stopTimer函数之后,TimerTest继续启动。为了检查计时器条件,我们使用了print和print-in-timeracontest返回nil var timerTest: Timer? = nil func startTimer () { timerTest = Timer.scheduledTimer( timeInterval: TimeI

我们调用startTimer函数来启动计时器。当我们想要停止它时,我们调用stopTimerTest函数,但在调用stopTimer函数之后,TimerTest继续启动。为了检查计时器条件,我们使用了print和print-in-timeracontest返回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
}

检查,您是否真的调用了
stopTimerTest()
,因为
timerTest.invalidate()
用于停止计时器是正确的

func stopTimerTest() {
    print("stopTimer")
    timerTest.invalidate()
}

很可能您已经调用了两次
startTimer
,但没有调用
stopTimerTest
。如果这样做,您将丢失指向原始计时器的指针,并且永远无法使其无效

典型的方法是将失效管理作为设置的一部分:

var timerTest : Timer? = nil {
    willSet {
        timerTest?.invalidate()
    }
}
然后停止只是设置为零:

func stopTimerTest() {
    timerTest = nil
}

尝试对代码进行以下更改:

首先,您必须更改声明timerTest的方式

var timerTest : Timer?
然后在实例化前的
startTimer
中检查
timerTest
是否为零

func startTimer () {
  guard timerTest == nil else { return }

  timerTest =  Timer.scheduledTimer(
      timeInterval: TimeInterval(0.3),
      target      : self,
      selector    : #selector(ViewController.timerActionTest),
      userInfo    : nil,
      repeats     : true)
}
最后,在您的
stopTimerTest
中,如果它不是零,您将使
timerTest
无效

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

确保当您调用
StartTimer
时,它是
nil
,并且如果您调用
StartTimer
两次而没有调用
StopTimer
,请确保。您将丢失原始指针,并且无法停止它

 var timer : Timer? = nil {
        willSet {
            timer?.invalidate()
        }
    }
启动和停止计时器,如

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
}

尝试声明
var timerTest:Timer?
然后在
startTimer
中,在实例化add
if timerTest==nil{您的实例化}
stopTimerTest
add
if timerTest!=nil{your code}
如果timerTest==nil{your instantiation}变得更加明亮。你能发布一些瓦迪安建议编译的代码吗?@mat先生,你的评论就是我问题的答案。如果你能回答,我可以核对一下。当然,如果你想的话,没有压力。@希望我很高兴它解决了你的问题。我刚才已经回答了。我还假设它会在重置它的值时调用invalidate。。。很好的解决方案。。。也可以使用扩展名:)这是我的问题=>“您将丢失指向原始计时器的指针,并且永远无法使其无效”。感谢这是定时器失效的最优雅的解决方案。提前谢谢!还记得null safe timerTest?.invalidate(),一种更干净、更快捷的方法吗?这很有趣。我不知道人们已经开始“宣传”他们自己的答案
guard timerTest==nil,否则{return}
很重要