How to invalidate an NSTimer that was started multiple times

∥☆過路亽.° 提交于 2019-12-12 04:18:24

问题


I made a practice project in Swift to learn how NSTimer works. There is one button to start the timer and one button to invalidate it. It works fine when I tap each button once. However, when I tap the start timer button multiple times, I am no longer able to invalidate it.

Here is my code:

class ViewController: UIViewController {

    var counter = 0
    var timer = NSTimer()

    @IBOutlet weak var label: UILabel!

    @IBAction func startTimerButtonTapped(sender: UIButton) {
        timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)
    }

    @IBAction func cancelTimerButtonTapped(sender: UIButton) {
        timer.invalidate()
    }

    func update() {
        ++counter
        label.text = "\(counter)"
    }
}

I have seen these questions but I wasn't able to glean an answer to my question from them (many are old Obj-C pre-ARC days and others are different issues):

  • NSTimer() - timer.invalidate not working on a simple stopwatch?
  • Using an NSTimer in Swift
  • NSTimer doesn't stop
  • Unable to invalidate (Stop) NSTimer
  • NSTimer doesn't stop with invalidate
  • Can't invalidate, stop countdown NSTimer - Objective C
  • IOS: stop a NSTimer

回答1:


You can add timer.invalidate() before starting a new timer in startTimerButtonTapped if you want to reset the timer each time the "start" button is tapped:

@IBAction func startTimerButtonTapped(sender: UIButton) {
    timer.invalidate()
    timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)
}

I was going to update with an explanation but @jcaron already did it in the comment, so I'm just quoting his text, no need to change it:

Every time you tap on the "Start Timer" button, you create a new timer, while leaving the previous one running, but with no reference to it (since you've overwritten timer with the new timer you just created). You need to invalidate the previous one before you create the new one.




回答2:


I would like to suggest you to set timer to nil when press on cancel button. And don't forget to set counter =0 When invalidating the Timer.



来源:https://stackoverflow.com/questions/34087873/how-to-invalidate-an-nstimer-that-was-started-multiple-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!