我正在设置计时器,以便在每个计时器完成后执行代码。不过,NSTimer 的计时似乎并不完全精确,过了一会儿,计时器似乎结束得有点早了。
我设置了以下内容来测试偏差。
(开始按钮在 Storyboard 中完成并链接到。)
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var startButton: UIButton!
//var mainTimer: NSTimer!
var counter: NSTimeInterval = 0.0
@IBAction func startButtonPressed(sender: AnyObject) {
startMainTimer()
startTimers()
}
func startMainTimer() {
let mainTimer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(ViewController.count), userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(mainTimer, forMode: NSRunLoopCommonModes)
}
func count() {
counter += 0.01
}
func startTimers() {
var lastTimeInterval: NSTimeInterval = 0.0
for _ in 0..<50 {
let timeInterval = lastTimeInterval + 1.0
lastTimeInterval = timeInterval
// Not setting up a repeating timer as intervals would be different in my original project where the deviation will be even worse.
let timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: #selector(ViewController.printTime), userInfo: nil, repeats: false)
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
}
}
func printTime() {
print(counter)
}
}
过了一会儿,计时器将提早十分之一秒甚至更多。 我应该使用 NSDate 以获得更好的时机,还是会过于复杂?使用 NSDate 会怎样?
非常感谢任何帮助/指点!
最佳答案
它永远不会完美,但您可以通过在目标选择器末尾安排下一次调用来阻止它复合。每次根据当前时间和您希望它触发的时间计算一个新的间隔。
编辑:我从一个非常古老的项目中抓取了一些代码来给出这个想法(这就是它在 Obj-C 中的原因)——你想要这样的东西但不完全是:
- (void)constantIntervalTimer {
static const NSTimeInterval secondsBetweenMessageSend = 1.0;
if ( !self.timerShouldStop ) {
NSDate *startTime = [NSDate date];
// your code here, it should take less than a
// second to run or you need to increase the timer interval
// figure out the right time to preserve the interval
NSTimeInterval waitTime = secondsBetweenMessageSend -
[[NSDate date] timeIntervalSinceDate:startTime];
// in case your code runs in more than the interval,
// we just call back immediately
if (waitTime < 0.0)
waitTime = 0.0;
[NSTimer scheduledTimerWithTimeInterval: waitTime
target:self selector:@selector(constantIntervalTimer)
userInfo:nil repeats:NO];
}
}
调用此消息后,它将持续每秒调用一次,直到您将名为 timerShouldStop 的属性设置为 YES。您必须声明和定义此属性并在您的 init 中将其设置为 NO 才能使此消息生效。
关于ios - NSTimer 不够精确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36356961/