Swift: How to invalidate a timer if the timer star

2019-03-02 18:06发布

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?

标签: swift nstimer
1条回答
We Are One
2楼-- · 2019-03-02 18:36

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).

查看更多
登录 后发表回答