从Swift中的功能使计时器失效 [英] Invalidate Timer from Function in Swift
问题描述
我有一个用 Swift
编写的应用程序,并且在 viewDidLoad
中声明了 NSTimer
;计时器每秒运行一次功能.
I have an app written in Swift
with an NSTimer
declared in the viewDidLoad
; the timer runs a function once every second.
这是我的 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()
但是,由于计时器位于 viewDidLoad
中,而不是函数中,或者未在函数中声明过,因此该函数无法访问 checkStateTimer
.
However, because the timer is in the viewDidLoad
and not the function or declared earlier, the function cannot access the checkStateTimer
.
麻烦的是,我无法在 viewDidLoad
之外(即仅在类中)声明计时器,因为它会导致错误.
Trouble is, that I can't declare the timer outside the viewDidLoad
(i.e just in the class) because it results in an error.
所以,我的问题是,如何获取视图,以便它将在 viewDidLoad
上启动计时器,但是能够在函数运行时暂停计时器.如何做到这一点的最佳方法,以便它可以停止计时器?
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?
推荐答案
将您的计时器声明为类变量:
Declare your timer as a class variable:
var checkStateTimer: NSTimer!
然后在viewDidLoad()中进行设置:
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()
}
这篇关于从Swift中的功能使计时器失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!