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()

选择器触发一次,然后在窗口关闭或最小化后才会再次触发。

还有谁?有什么建议么?

4

3 回答 3

4

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

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()
    })
于 2016-04-01T18:25:58.003 回答
1
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 Apples 文档中对我有用,并没有说明 dispatch_async。有什么理由使用它...只是好奇...还在学习

使用 timerWithTimeInterval:invocation:repeats: 或 timerWithTimeInterval:target:selector:userInfo:repeats: 类方法来创建计时器对象,而无需在运行循环中调度它。(创建完成后,你必须通过调用相应 NSRunLoop 对象的 addTimer:forMode: 方法手动将定时器添加到运行循环中。)

于 2016-04-01T22:09:11.280 回答
0
    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 中自动处理。在同一线程上手动执行此操作可修复它。

感谢大家的帮助和建议。

于 2016-04-01T19:21:53.427 回答