NSTimer的准确性 [英] Accuracy of NSTimer
问题描述
我正在尝试使用NSTimer创建一个秒表样式的计时器,该计时器每0.1秒递增一次,但有时似乎运行得太快..
I am trying to use NSTimer to create a Stop-watch style timer that increments every 0.1 seconds, but it seems to be running too fast sometimes ..
这是我的操作方式:
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用作计时器停止的时间...
This will display the value of the timer in the Label, and I can later utilize maxTime as the time when the Timer is stopped ...
问题是它运行不准确.
有没有一种方法可以确保NSTimer每0.1秒准确触发一次?我知道NSTimer是不准确的,并且我要进行调整以使其准确.
Is there a method where I can make sure that NSTimer fires strictly every 0.1 seconds accurately ? I know that NSTimer isn't accurate , and I'm asking for a tweak to make it accurate.
谢谢
推荐答案
以下是您可以用来做您想做的事情的类:
Here's a class you can use to do what you want:
@interface StopWatch()
@property ( nonatomic, strong ) NSTimer * displayTimer ;
@property ( nonatomic ) CFAbsoluteTime startTime ;
@end
@implementation StopWatch
-(void)dealloc
{
[ self.displayTimer invalidate ] ;
}
-(void)startTimer
{
self.startTime = CFAbsoluteTimeGetCurrent() ;
self.displayTimer = [ NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector( timerFired: ) userInfo:nil repeats:YES ] ;
}
-(void)stopTimer
{
[ self.displayTimer invalidate ] ;
self.displayTimer = nil ;
CFAbsoluteTime elapsedTime = CFAbsoluteTimeGetCurrent() - self.startTime ;
[ self updateDisplay:elapsedTime ] ;
}
-(void)timerFired:(NSTimer*)timer
{
CFAbsoluteTime elapsedTime = CFAbsoluteTimeGetCurrent() - self.startTime ;
[ self updateDisplay:elapsedTime ] ;
}
-(void)updateDisplay:(CFAbsoluteTime)elapsedTime
{
// update your label here
}
@end
关键点是:
- 通过将秒表启动时的系统时间保存到变量中来进行计时.
- 秒表停止时,通过从当前时间中减去秒表开始时间来计算经过的时间
- 使用计时器更新您的显示.无论您的计时器是否准确,这都不重要.如果您要保证至少每隔0.1秒更新一次显示,则可以尝试将计时器间隔设置为最小更新时间(0.05s)的1/2.
这篇关于NSTimer的准确性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!