Nstimer计数错误 [英] Nstimer count wrong

查看:76
本文介绍了Nstimer计数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对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:


计时器不是一种实时机制;仅当已添加计时器的
运行循环模式之一正在运行并且能够
检查计时器的触发时间是否经过时,它才会触发。由于典型的运行循环管理着各种
输入源,因此计时器的时间间隔
的有效分辨率被限制在50-100
毫秒的数量级。如果计时器的触发时间发生在长时间的调用过程中,或者
在运行循环处于不监视计时器的模式下发生,则
计时器不会启动,直到运行循环下次检查计时器为止。
因此,计时器可能触发的实际时间可能是在计划的触发时间之后的
a相当长的一段时间。

A timer is not a real-time mechanism; it fires only when one of the run loop modes to which the timer has been added is running and able to check if the timer’s firing time has passed. 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.

通过每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计数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆