Search code examples
swiftnstimer

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


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?


Solution

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