dugla dugla - 4 months ago 46
Swift Question

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?


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

class ViewController: UIViewController {
    var count = 0

    override func 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
        } else {
            print("Timer invalidated")