Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

objective c - Accuracy of NSTimer

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 ..

This is how I've done it:

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

and then:

-(void)updateTimeLabel
{
    maxTime=maxTime+0.1;
    timerLabel.text =[NSString stringWithFormat:@"%.1f Seconds",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 ...

THe problem is that it runs very inaccurately.

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.

THanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to the NSTimer documentation, it is not meant to be accurate.

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.

You may want to use the dispatch_after function from GCD, which is suggested by the official documentation for this exact purpose (creating a timer).

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


By the way, I agree with Caleb's answer. You probably are going to solve your problems if you don't accumulate error like your doing right now. If you store the start date and recalculate the time at every iteration using the -timeIntervalSince: method, you're gonna end up with an accurate UI update, regardless of the timer precision.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...