定时器在模拟器和设备上的行为有所不同

时间:2010-09-01 09:11:21

标签: iphone ios-simulator nstimer

我的问题如下:

timer1 = [NSTimer scheduledTimerWithTimeInterval:1.0/5 target:self
         selector:@selector(Loop1) userInfo:nil repeats:YES];

timer2 = [NSTimer scheduledTimerWithTimeInterval:1.0/5 target:self 
         selector:@selector(Loop2) userInfo:nil repeats:YES];

timer3 = [NSTimer scheduledTimerWithTimeInterval:1.0/20 target:self 
         selector:@selector(Loop3) userInfo:nil repeats:YES];

timer4 = [NSTimer scheduledTimerWithTimeInterval:1.0/10 target:self 
         selector:@selector(Loop4) userInfo:nil repeats:YES];

timer5 = [NSTimer scheduledTimerWithTimeInterval:1.0/5 target:self 
         selector:@selector(Loop5) userInfo:nil repeats:YES];

我用这5个计时器在iPhone上移动帧。但timer3timer4在iPod和模拟器上的表现不同。 iPod上的timer3timer4比我想要实现的要慢,并且在模拟器上运行良好。

请说明问题出在哪里?

4 个答案:

答案 0 :(得分:1)

NSTimers无法安排2个或更多方法同时启动(特别是在只有1个处理器核心的iOS设备上)。如果第一个计时器任务很慢,第二个计时器任务将会迟到。

在模拟器上,第一个任务可能运行速度提高10倍或更快(由于原始CPU和内存性能),使得第二个任务更加迟钝,以至于您没有注意到它已经迟到了。

使每个任务更快,或者使定时器倾斜,以使任务不重叠。或者将每个计时器任务内部的操作结合起来,如果该任务发生在某个最不常见的多个时隙。

答案 1 :(得分:0)

您的问题可能只是性能问题。如果设备不仅耗尽资源,请使用活动监视工具和设备上运行的应用程序进行检查。

我的猜测是你要求设备每10秒钟重复三次操作,这可能会超出其容量,具体取决于操作。

也许你可以放弃Loop3和Loop4的代码行?

答案 2 :(得分:0)

如果您需要高精度,则不能依赖计时器。这取决于设备负载。模拟器在Mac上运行,因此您将获得更高的精度。但该设备的功能不如Mac强大。所以会有明显的延迟。

为什么你需要这样的计时器?你想尝试动画吗?在这种情况下,有更好的选择。特别关注UIView动画而不是计时器。

答案 3 :(得分:0)

根据文档:http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html

the effective resolution of the time interval for a timer is limited to on the order of 50-100 milliseconds

你的两个麻烦的计时器是1/10和1/20秒,恰好是100和50毫秒。你正在调试NSTimer可以处理的最好的时间片,你应该期待一些不可靠的事情。