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。
为什么这段代码可以工作?
scheduledTimer
已经将Timer
添加到RunLoop
,这就是为什么下一行甚至不必要的原因。
见Timer.scheduledTimer(timeInterval:target:selector:userInfo:repeats:)
创建一个计时器,并在默认模式下在当前运行循环上对其进行计划。
第二行通过a
只是因为你已经宣布A
是一个Timer
,这可能是一个错误:
// A should not be a Timer!
class A: Timer {