我正在尝试使用 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
}
进度条仅在我编译并运行项目后第一次出现。录制完成后,该应用程序将转至另一个 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/