-1
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?

Rob
  • 415,655
  • 72
  • 787
  • 1,044
Jay
  • 267
  • 2
  • 7

1 Answers1

3

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 {
Alexander
  • 59,041
  • 12
  • 98
  • 151
Sulthan
  • 128,090
  • 22
  • 218
  • 270