问题
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