ios - Swift:防止 NSTimer 自动启动

标签 ios swift nstimer

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

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
        }

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

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

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

最佳答案

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

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
  }
  ...
}

关于ios - Swift:防止 NSTimer 自动启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33584765/

相关文章:

ios - 人脸对比

ios - Swift 中的泛型和 EXC_BAD_ACCESS

ios - 在 Swift 中单击单元格后 Xcode 触发操作

ios - Swift 中 NSTimer 的问题

objective-c - 是否可以更改 NSTimer 的用户信息?

jquery - 滚动后,在错误的区域检测到触摸(iPad/网站)

objective-c - 在 Objective-C 中读取文件时处理换行符

Swift 检查值是否为数组类型(任何类型)

ios - 核心数据跳过获取函数 Swift

cocoa-touch - 为什么通过 AV Foundation 播放音频会在慢速连接时阻塞 UI?