iOS Swift -防止计时器#fire()打开#invalidate()

lyr7nygr  于 2023-01-22  发布在  iOS
关注(0)|答案(1)|浏览(152)

给定以下代码

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

正如你所看到的,当我无效的计时器火灾的权利!
有什么办法可以防止吗?
我看了苹果的文档,上面写着“停止计时器再次启动,并请求将其从运行循环中删除”,我将其解释为“当您使计时器无效时,计时器不再启动”。我错了吗?

lyfkaqu1

lyfkaqu11#

完成后,在DispatchQueue.main.async中再次调用startMyTimer()。在该函数中初始化计时器。

相关问题