给定以下代码
private var myTimer: Timer? = nil
override func viewDidLoad() {
super.viewDidLoad()
// start my Timer
startMyTimer()
// stop timer and restart
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) {
self.myTimer!.fire()
print("my timer: invalidating \(Date.now.mediumTimeLocalizedDescription)")
self.myTimer!.invalidate()
self.myTimer = nil
self.startMyTimer()
}
}
private func startMyTimer() {
myTimer = Timer.scheduledTimer(withTimeInterval: 10, repeats: true) { timer in
print("my timer: Fired \(Date.now.mediumTimeLocalizedDescription)")
}
myTimer!.fire()
}
我得到了以下输出:
my timer: Fired 14:27:14
my timer: Fired 14:27:17
my timer: invalidating 14:27:17
my timer: Fired 14:27:17
my timer: Fired 14:27:27
预期产出:
my timer: Fired 14:27:14
my timer: Fired 14:27:17
my timer: invalidating 14:27:17
my timer: Fired 14:27:27
正如你所看到的,当我无效的计时器火灾的权利!
有什么办法可以防止吗?
我看了苹果的文档,上面写着“停止计时器再次启动,并请求将其从运行循环中删除”,我将其解释为“当您使计时器无效时,计时器不再启动”。我错了吗?
1条答案
按热度按时间lyfkaqu11#
完成后,在DispatchQueue.main.async中再次调用startMyTimer()。在该函数中初始化计时器。