gpt4 book ai didi

iphone - Ntimer 计数错误

转载 作者:行者123 更新时间:2023-11-28 20:27:35 26 4
gpt4 key购买 nike

我对 NSTimer 有疑问。我开始并每 100 毫秒重复一次,我有一个计数器来检查我是否跑了 10 秒。问题是它在将近 1 分钟内停止,而不是 10 秒。这是我的代码

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

我不明白为什么会出错。有人可以告诉我为什么吗?谢谢。

最佳答案

NSTimers 不能保证精确到超过 100 毫秒左右。 The NSTimer documentation说:

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 秒过去时,它可能与您的预期相去甚远。

如果您想在 10 秒后采取一些行动,为什么不直接将计时器设置为在 10 秒后触发?

NSLog( @"start" );
timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(checkTimer) userInfo:nil repeats:YES];

-(void)checkTimer
{
NSLog(@"i got it");
}

此外,您是否在主线程上进行流式传输? NSTimers 在主 runloop 上工作,所以如果你阻塞了主线程,定时器在它被解除阻塞之前不会触发。

关于iphone - Ntimer 计数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13446766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com