有没有修复/解决方法?
编辑:这是我如何启动计时器:
NSTimer *clockTimer = [[NSTimer alloc] initWithFireDate:[NSDate nextFullMinuteDate] interval:60.0 target:self selector:@selector(updateClocks:) userInfo:nil repeats:YES];[[NSRunLoop currentRunLoop] addTimer:clockTimer forMode:NSDefaultRunLoopMode];[clockTimer release];
顺便说一句,我已经尝试在火灾日期添加几毫秒,这似乎有所帮助,但看起来找到一个适当的间隔添加是命中注定.
编辑2:好的,所以我手动设置我的计时器在一整分钟后开始0.05秒,然后在60.0秒后再次开始.现在这是我在被调用方法中记录的内容:
0.0487280.0471530.0464840.0448830.043103
正如您所看到的,NSTimer实际上并不使用60秒的时间间隔,而是稍微短一些.
解决方法 从NSTimer
docs: 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.
这意味着NSTimer非常不准确.
如果您编写“秒表”,您可以使用NSTimer向用户显示结果,而NIRTimer
(我最喜欢的类之一)会记录时间.这概述如下:
NIRTimer *nirTimer;NSTimer *timer;- (voID)start { nirTimer = [[NIRTimer alloc]init]; timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES]; [nirTimer start];- (voID)timerFired:(NSTimer *)timer { [self displayTimetoUser:[nirTimer seconds]];}
在上面的代码中,NSTimer可能不准确,但精确的时间由NIRTimer保存,每隔0.01秒向用户显示一次.
如果您确实需要在特定时间运行特定代码,我找到的最佳解决方案是使用NSThread和usleep():
BOol timerRunning;- (voID)start { timerRunning = YES; [NSThread detachNewThreadSelector:@selector(timer) toTarget:self withObject:nil]; //make a new thread}- (voID)timer { NSautoreleasePool *pool = [[NSautoreleasePool alloc]init]; //Make an autorelease pool since we're in a new thread NIRTimer *timer = [[NIRTimer alloc]init]; //Make an NIRTimer while (timerRunning) { [timer reset]; [timer start]; [self doSomething]; usleep(10000 - [timer microseconds]); //Wait for .01 seconds which is 10000 microseconds (a microsecond is 1/1000000th of a second) - the time it took to accomplish whatever we were doing } //Clean up [timer release]; [pool release];}
在这种情况下,将timerRunning设置为NO以停止计时器.您可能还想使用[self performSelectorOnMainThread:@selector(doSomething)withObject:nil waitUntilDone:NO]而不是[self doSomething],如果您要做的事情不是线程安全的.
有关精彩的线程世界的更多信息,请查看Threading Programming Guide.
总结以上是内存溢出为你收集整理的可可 – NSTimer不准确?全部内容,希望文章能够帮你解决可可 – NSTimer不准确?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)