【问题标题】:Why does this Timer/RunLoop code work? It shouldn’t为什么这个 Timer/RunLoop 代码有效?不应该
【发布时间】:2019-03-08 17:23:50
【问题描述】:
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】:

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

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

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

    第二行通过a 只是因为您已将A 声明为Timer,这可能是一个错误:

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

    【讨论】:

    • 非常感谢!你非常非常善良
    猜你喜欢
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    • 2021-08-17
    • 2017-04-20
    • 1970-01-01
    相关资源
    最近更新 更多