2

我正在我的游戏中实现倒计时方法,它将使用 15 秒倒计时。我一直在寻找不同的方法来实现这一点,并相信 NSTimer 是要走的路。

但是,有人告诉我它可能会受到处理器速度等的影响,我的问题是这是否属实,如果是这样,我该如何应对?

我已经看到了这个:NSTimer但不完全理解它的影响。

有没有其他方法可以保证 15 秒的停机时间和所有设备?

4

3 回答 3

1

没看懂你最后一句话

然而,我相信你的朋友是对的,它与实际的倒计时相比略有偏差,但我向你保证,差异是如此之小以至于它并不明显,尤其是对于游戏而言。

差异的原因是因为您将 NSTimer 设置为在一秒钟内执行,当它执行时它会更新屏幕上的倒计时然后重复。我的猜测是 NSTimer 直到完成执行您的方法后才会开始重复,因此每个 NSTimer 秒都比实际秒长几分之一秒。

Apple 可能比我领先一步,并在执行之前调用重复,但是,我不确定。

无论哪种方式,就像我说的那样,除非您正在做一些重要的事情而不是每秒更新屏幕,否则您的用户根本不应该注意到差异。

于 2012-11-21T23:10:23.880 回答
0

NSTimer 对于大多数用途应该没问题。这不会是准确的——这个时间段会比你设置的稍长,但在良好的条件下只有很小的时间——想想毫秒。然而,NSTimer 通过一个 runloop 触发,所以它的准确性取决于那个 runloop 不忙。您可以通过在其自己的线程上使用专用的运行循环来最小化问题,但如果系统繁忙,您仍然会看到计时器的周期略有延长。

因此,虽然 CPU 速度与其他此类因素之间没有先天关系,但更快的硬件将能够由于不经常忙碌而更好地跟上。

Note also that a repeating NSTimer will not phase shift - it'll be as accurate set to an interval of 1s as at 15s. The only caveat is that if your handler is still running when the next fire should occur, that fire won't happen at all. e.g. if you take 1.1 seconds, the gap between firings will jump up to 2s.

An alternative to runloops & NSTimers is dispatch_after. It's not likely to be any more accurate though, and its skid is still contingent on the target queue (likely one of the default concurrent queues) not being busy when it fires.

于 2012-11-22T03:36:15.773 回答
0

Theory: The NSTimer is not directly affected by the processor speed. A timer running for 1 minute on a Gen 2 device should also represent 1 minute on a much newer device.

Now that was the theory :), but in actuality, the processor speed not only affects your timers, but the general overall speed of your app (e.g., how fast your views change, how soon your music starts after you have pressed a button, etc). The only (or best test) is to repeatedly test your app on the types of devices that you are going to target. Test early, test often :)

You can not (based on my experiences) guarantee exactly time T on any device. You can however get times that are close on average to your expected time T.

于 2012-11-22T03:57:04.570 回答