为什么这个Timer / RunLoop代码有效?它不应该

问题描述 投票:-1回答: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()
    }
}

请注意,在RunLoop.current.add(a, forMode: .common),我没有将a.myTimer添加到runloop,但是“意外地”将a添加到了runloop。

为什么这段代码可以工作?

ios swift nsrunloop
1个回答
3
投票

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

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

创建一个计时器,并在默认模式下在当前运行循环上对其进行计划。

第二行通过a只是因为你已经宣布A是一个Timer,这可能是一个错误:

// A should not be a Timer!
class A: Timer {
© www.soinside.com 2019 - 2024. All rights reserved.