更新到 Xcode 7.3/Swift 2.2 后计时器停止工作

Timer stopped working after update to Xcode 7.3/Swift 2.2

更新到Swift 2.2和Xcode 7.3后,我的重复NSTimer停止重复了。

let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(rotate), userInfo: nil, repeats: true)
timer.fire()

选择器触发一次,然后在 window 关闭或最小化之前不会再次触发。

还有其他人吗?有什么建议吗?

定时器需要始终在同一个线程中进行调度或失效,您可能是在异步块中调用它?尝试在主队列中安排它:

dispatch_async(dispatch_get_main_queue(), { () -> Void in
    let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(rotate), userInfo: nil, repeats: true)
    timer.fire()
    })
    dispatch_async(dispatch_get_main_queue()) {
        self.timer = NSTimer(timeInterval:1.0, target:self, selector: #selector(self.rotate), userInfo:nil, repeats:true)
        NSRunLoop.currentRunLoop().addTimer(self.timer!, forMode: NSRunLoopCommonModes)
    }

这是一个线程问题,或者未正确添加或在 NSRunLoop 中自动处理。在同一个线程上手动执行此操作修复了它。

感谢大家的帮助和建议。

func startTimer() {
    let timer = NSTimer(timeInterval: 1, target: self, selector: #selector(MainViewController.updateLabel), userInfo: nil, repeats: true)
    NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
}

这对我来说适用于 Swift 2.2 Apple 文档没有说明任何关于 dispatch_async 的内容。有什么理由要用吗...只是好奇...还在学习中

Use the timerWithTimeInterval:invocation:repeats: or timerWithTimeInterval:target:selector:userInfo:repeats: class method to create the timer object without scheduling it on a run loop. (After creating it, you must add the timer to a run loop manually by calling the addTimer:forMode: method of the corresponding NSRunLoop object.)