如何使多次启​​动的 NSTimer 无效 [英] How to invalidate an NSTimer that was started multiple times

查看:48
本文介绍了如何使多次启​​动的 NSTimer 无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Swift 中做了一个练习项目来学习 NSTimer 是如何工作的.有一个按钮可以启动计时器,还有一个按钮可以使计时器无效.当我点击每个按钮一次时,它工作正常.但是,当我多次点击启动计时器按钮时,我不再能够使其无效.

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.

这是我的代码:

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 天和其他是不同的问题):

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):

推荐答案

如果你想在 startTimerButtonTapped 开始一个新的计时器之前添加 timer.invalidate()每次点击开始"按钮时重置计时器:

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

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

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.

这篇关于如何使多次启​​动的 NSTimer 无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆