问题
I have an app written in Swift with an NSTimer declared in the viewDidLoad; the timer runs a function once every second.
Here's the code inside my viewDidLoad():
let checkStateTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "callCheckState:", userInfo: nil, repeats: true)
Currently, I have another function which is called which I want to pause the timer. It should, I believe, use:
checkStateTimer.invalidate()
However, because the timer is in the viewDidLoad and not the function or declared earlier, the function cannot access the checkStateTimer.
Trouble is, that I can't declare the timer outside the viewDidLoad (i.e just in the class) because it results in an error.
So, my question is, how do I get the view so that it will start the timer on viewDidLoad, but be able to pause the timer when the function runs. How is the best way of doing this so that it can stop the timer?
回答1:
Declare your timer as a class variable:
var checkStateTimer: NSTimer!
And then set it in viewDidLoad():
func viewDidLoad() {
super.viewDidLoad()
checkStateTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "callCheckState:", userInfo: nil, repeats: true)
}
Then in your function invalidate the timer:
func someFunction() {
checkStateTimer.invalidate()
}
来源:https://stackoverflow.com/questions/32550465/invalidate-timer-from-function-in-swift