如何使多次启​​动的 NSTimer 失效

How to invalidate an NSTimer that was started multiple times

我在 Swift 中做了一个练习项目来学习 NSTimer 是如何工作的。一键启动定时器,一键取消定时器。当我点击每个按钮一次时它工作正常。但是,当我多次点击开始计时器按钮时,我无法再使其无效。

这是我的代码:

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)"
    }
}

我看过这些问题,但我无法从他们那里得到我的问题的答案(很多都是旧的 Obj-C pre-ARC 天,其他是不同的问题):

如果您想在每次点击 "start" 按钮时重置计时器,您可以在 startTimerButtonTapped 中启动新计时器之前添加 timer.invalidate()

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

我本来打算更新解释,但@jcaron 已经在评论中做了,所以我只是引用他的文字,无需更改:

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.

我建议您在按下取消按钮时将计时器设置为零。 并且不要忘记设置 counter =0 使定时器无效时。