Search code examples
swiftreferencenstimer

How do I invalidate to a Timer placed on the RunLoop


In a Swift app I am using a Timer. I prefer not to keep a reference to the Timer after I create it and insert it in the Runloop. I want to be able to invalidate it. Is there a way to do this without keeping around a reference?


Solution

  • The timer's selector can keep a reference to the Timer object. Try this:

    class ViewController: UIViewController {
        var count = 0
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let _ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.timerFired(timer:)), userInfo: nil, repeats: true)
        }
    
        // Run the timers for 3 times then invalidate it
        func timerFired(timer: Timer) {
            if count < 3 {
                count += 1
                print(count)
            } else {
                timer.invalidate()
                print("Timer invalidated")
            }
        }
    }