Search code examples
iosswiftnsrunloop

Why does this Timer/RunLoop code work? It shouldn’t


class A: Timer {
    var myTimer: Timer!
}

class TimerTestViewController: UIViewController {
    var a = A()

    override func viewDidLoad() {
        super.viewDidLoad()
        a.myTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerRun), userInfo: nil, repeats: true)
        RunLoop.current.add(a, forMode: RunLoop.Mode.common)

        a.myTimer.fire()
    }
}

Notice in RunLoop.current.add(a, forMode: .common) that i didn't add a.myTimer to runloop but “accidentally” added a to the runloop.

why does this code work at all?


Solution

  • scheduledTimer has already added the Timer to a RunLoop and that's why the next line is not even necessary.

    See Timer.scheduledTimer(timeInterval:target:selector:userInfo:repeats:)

    Creates a timer and schedules it on the current run loop in the default mode.

    The second line passes with a only because you have declared A to be a Timer which is probably an error:

    // A should not be a Timer!
    class A: Timer {