计时器不会在 segue 上停止



我正在实例化这样的计时器:

func runTimer() {
  DispatchQueue.main.async {
    if self.timer.isValid == false {
      self.timer = Timer.scheduledTimer(timeInterval: 0.025, target: self, selector: (#selector(ResultVCViewController.updateTimer)), userInfo: nil, repeats: true)
      RunLoop.current.add(self.timer, forMode: .commonModes)          
      }
    }
  }

并像这样解除分配它:

func stopTimer() {
  DispatchQueue.main.async {
    if self.timer.isValid {
      self.timer.invalidate()
      self.isTimerRunning = false
      print("stopped timer")
    } else {
      print("timer isn't running!")
    }
  }
}

当这样调用时,stopTimer()不会被调用(没有控制台输出,计时器仍在运行,如果我添加断点,它会被忽略,但会执行 segue(:

@IBAction func aboutLicensebtn(_ sender: UIBarButtonItem) {
  //debug
  stopTimer()
  performSegue(withIdentifier: "AboutLicense", sender: nil)
}

这按预期工作:

@IBAction func goBack(_ sender: UIBarButtonItem) {
  stopTimer()
  self.dismiss(animated: true, completion: nil)
}

执行 segue 时如何停止计时器?

编辑:计时器在放入viewDidDisappear时停止,但我不希望这种行为。

编辑:我也尝试在 main 上执行 segue,但结果没有变化。

澄清为什么我以我的方式启动和停止计时器:

它被添加到用于.commonModesRunLoop中,因此计时器不会在滚动视图时停止。

它在 main 上启动和停止

,以确保它在同一线程上启动和停止。

不要计划计时器添加到运行循环中。

启动和停止计时器的最可靠方法是使用可选属性并检查这一点(根本不需要调度到主队列(:

var timer : Timer?

func runTimer() {
    if timer == nil {
       timer = Timer.scheduledTimer(timeInterval: 0.025, 
                     target: self, 
                     selector: #selector(updateTimer), 
                     userInfo: nil, 
                     repeats: true)
    }
}

func stopTimer() {
    if timer != nil {
      timer!.invalidate()
      timer = nil
      print("stopped timer")
    } else {
      print("timer isn't running!")
    }
}

最新更新