objective-c - NSTimer 的精度

标签 objective-c nstimer

我正在尝试使用 NSTimer 创建一个每 0.1 秒递增一次的秒表式计时器,但有时它似乎运行得太快了。

我是这样做的:

Timer =[NSTimer scheduledTimerWithTimeInterval: 0.1 target:self selector:@selector(updateTimeLabel) userInfo:nil repeats: YES];

然后:

-(void)updateTimeLabel
{
    maxTime=maxTime+0.1;
    timerLabel.text =[NSString stringWithFormat:@"%.1f Seconds",maxTime];
}

这将在 Label 中显示计时器的值,我稍后可以利用 maxTime 作为计时器停止的时间......

问题是它运行的很不准确。

有没有一种方法可以确保 NSTimer 准确地每 0.1 秒触发一次?我知道 NSTimer 不准确,我要求进行调整以使其准确。

谢谢

最佳答案

根据NSTimer文档,它并不意味着准确。

Because of the various input sources a typical run loop manages, the effective resolution of the time interval for a timer is limited to on the order of 50-100 milliseconds. If a timer’s firing time occurs during a long callout or while the run loop is in a mode that is not monitoring the timer, the timer does not fire until the next time the run loop checks the timer. Therefore, the actual time at which the timer fires potentially can be a significant period of time after the scheduled firing time.

您可能想要使用 dispatch_after来自 GCD 的函数,由 official documentation 建议为了这个确切的目的(创建一个计时器)。

If you want to perform a block once after a specified time interval, you can use the dispatch_after or dispatch_after_f function.


顺便说一下,我同意 Caleb 的回答。如果您不像现在那样累积错误,您可能会解决您的问题。 如果您存储开始日期并在每次迭代时使用 -timeIntervalSince: 方法重新计算时间,无论计时器精度如何,您最终都会获得准确的 UI 更新。

关于objective-c - NSTimer 的精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17414344/

相关文章:

ios - 在 iOS 上的图像中查找非透明填充的 CGRect

ios - NSLocalized 从字符串文件创建不同的字符串

ios - Swift 中的字符指针

objective-c - 将 CoreData 添加到现有项目

编译后的 Objective-c/Swift 方法和变量名称

ios - Ntimer 实现

Swift - 方法存在,但错误 :unrecognized selector sent to instance

iphone - UIView 和 NSTimer 不释放内存

iphone - NSTimer 暂停不起作用

swift - [__NSCFTimer copyWithZone :]: unrecognized selector sent to instance