问题描述
我对NSTimer有问题。我每隔100ms重复一次,我有一个计数器检查我是否运行了10s。问题是它在1分钟左右(而不是10秒)内停止。
这是我的代码
I have a problem with NSTimer. I start and repeat it every 100ms and I have a counter to check if i runed 10s. The problem is it stoped in near 1 minute, not in 10s.Here is my code
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(checkTimer) userInfo:nil repeats:YES];
-(void)checkTimer
{
timerCount += 1;
if(timerCount == 1)
{
NSLog(@"start");
}
if(timerCount == 103)
{
NSLog(@"i got it");
}
}
这里是日志:
2012-11-19 08:57:42.063 Karagram[11708:540b] start
[Switching to process 8707 thread 0x2203]
2012-11-19 08:58:39.514 Karagram[11708:540b] i got it
I不明白为什么会出错。有人可以告诉我为什么?
谢谢。
I don't understand why it wrong. Somebody can tell me why?Thanks.
推荐答案
NSTimers的准确性不能保证在100毫秒左右。 NSTimer文档说:
NSTimers aren't guaranteed to be accurate to within more than 100 ms or so. The NSTimer documentation says:
通过每100毫秒触发一次,您就使错误变得更加复杂,因为如果每100毫秒关闭50毫秒,那么在经过10秒钟时它可能与您的预期相去甚远。
By having it fire every 100ms you're compounding the error, because if it's off 50 ms every 100ms, by the time 10s has passed it could be quite far from what you expect.
如果您想在10s后采取行动,为什么不将计时器设置为在10s后触发?
If you're wanting to take some action after 10s, why not just set the timer to fire after 10s?
NSLog( @"start" );
timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(checkTimer) userInfo:nil repeats:YES];
-(void)checkTimer
{
NSLog(@"i got it");
}
此外,您是否正在主线程上进行流传输? NSTimers在主运行循环上工作,因此,如果您要阻塞主线程,则直到取消阻塞后,定时器才会启动。
Also, are you doing your streaming on the main thread? NSTimers work on the main runloop, so if you're blocking the main thread, timers aren't going to fire until it's unblocked.
这篇关于Nstimer计数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!