Swift: How to invalidate a timer if the timer starts from a function?

和自甴很熟 提交于 2019-12-02 01:43:48

问题


I have a timer variable in a function like this:

timer = NSTimer()

func whatever() {
   timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerbuiltingo", userInfo: nil, repeats: true)
}

when I try to stop the timer in the resulting timerbuiltingo function like this:

func timerbuiltingo() {
   timer.invalidate()
   self.timer.invalidate()
}

It doesn't stop it. How should I be doing this?


回答1:


If you need to be able to stop the timer at any point in time, make it an instance variable.

If you will only ever need to stop it in the method it is called, you can have that method accept an NSTimer argument. The timer calling the method will pass itself in.

class ClassWithTimer {
    var timer = NSTimer()

    func startTimer() {
        self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerTick:", userInfo: nil, repeats: true)
    }

    @objc func timerTick(timer: NSTimer) {
        println("timer has ticked")
    }
}

With this set up, we can now either call self.timer.invalidate() or, within timerTick, we can call timer.invalidate() (which refers to the timer which called the method).



来源:https://stackoverflow.com/questions/29579237/swift-how-to-invalidate-a-timer-if-the-timer-starts-from-a-function

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