Invalidate Timer from Function in Swift

时光总嘲笑我的痴心妄想 提交于 2021-02-05 12:17:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!