为什么此Timer / RunLoop代码起作用?它不应该

时间:2019-03-08 17:23:51

标签: ios swift nsrunloop

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()
    }
}

RunLoop.current.add(a, forMode: .common)中,我没有向运行循环中添加a.myTimer,但“偶然地”向运行循环中添加了a

为什么这些代码完全起作用?

1 个答案:

答案 0 :(得分:3)

scheduledTimer已将Timer添加到RunLoop中,这就是为什么甚至不需要下一行的原因。

请参见Timer.scheduledTimer(timeInterval:target:selector:userInfo:repeats:)

  

创建一个计时器,并在默认模式下将其安排在当前运行循环中。

第二行仅通过a传递是因为您已将A声明为Timer,这可能是错误的:

// A should not be a Timer!
class A: Timer {
相关问题