Swift: 防止 NSTimer 自动启动

Swift: prevent NSTimer starting automatically

我正在尝试使用 NSTimer 在我的应用程序中增加录音时的进度条(参见屏幕截图)

let timedClock = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("Counting:"), userInfo: nil, repeats: true)

    internal func Counting(timer: NSTimer!) {
            if timeCount == 0 {
                //self.timedClock = nil
                stopRecording(self) //performs segue to another view controller
            } else {
                timeCount--;
                self.timer.text = "\(timeCount)"
            }
            print("counting called!")
            progressBar.progress += 0.2
        }

进度条仅在我编译和 运行 项目后第一次出现。录制完成后,该应用程序将转至另一个视图控制器以播放录制的音频。但是,当我返回记录视图时,timer/progress 栏会自动 运行s。我怀疑 NSTimer 对象在 NSRunLoop 上仍然存在。所以我想知道如何防止 NSTimer 自动 运行ning.

受此 SO thread 中答案的启发,我尝试了以下方法,但 NSTimer 仍然自动 运行s.

let timedClock = NSTimer(timeInterval: 1, target: self, selector: "Counting:", userInfo: nil, repeats: true)
        NSRunLoop.currentRunLoop().addTimer(timedClock, forMode: NSRunLoopCommonModes)

抱歉我的快速自我回答,因为我刚刚发现我可以使用 invalidate() 方法来防止计时器自动触发:

timedClock.invalidate()

希望对以后的人有所帮助!

发生这种情况是因为当您的控制器创建时,它的属性会自动初始化。根据 Apple Docs(和方法名称)scheduledTimerWithTimeInterval 创建和 return 预定计时器。因此,如果您只想创建计时器并通过触发器函数调用它,请像这样使用它:

class MyClass {

  var timer: NSTimer?
  ...
  func enableTimer() {
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("Counting:"), userInfo: nil, repeats: true)
  }

  func disableTimer() {
    timer?.invalidate()
    timer = nil
  }
  ...
}