如何使用 NSDate 运行倒计时?
我开发了一个应用程序,在其中运行倒计时器。计时器每秒触发一个方法。然而,当手机处于睡眠模式时,计时器会变慢甚至关闭。
我想我需要通过使用 NSDate 计算时间间隔来更新变量。有人知道该怎么做吗?
顺便说一句,我们的客户发送了以下反馈:
计时器问题似乎是由 事实上,代码假设 定时器通知消息是 恰好在一秒内交付,但是 不是。当应用程序运行时但是 手机处于待机状态,它使用 计时器更新倒计时器。 但计时器来得慢一些 不到一秒,所以倒计时 定时器已关闭。该应用程序应该是 重新设计以始终更新 基于当前的倒计时器 时间,而不是根据 计时器消息本身。 (在其他 话,当一秒消息 进来,总是假设 额外的时间已经过去了 计算剩余时间 从目标时间中减去。这 当你重新启动时会发生什么 应用程序——它计算出目标时间 和当前时间减一 来自另一个,并更新 屏幕计时器。嗯,就是这样 应该始终这样做。)
如果有人了解我们到底需要什么,请告诉我。
I have developed an application in which I'm running a countdown timer. The timer fires a method every second. However, when the phone is in sleep mode, the timer becomes slow or even turns off.
I think I need to update the variables by calculating the time intervals using NSDate. Does someone knows how to do this?
BTW, our client has sent the following feedback:
The timer problem appears to be caused
by the fact that the code assumes that
the timer notification messages are
delivered at exactly one second, but
aren't. When the app is running but
the phone is in standby, it uses the
timer to update the countdown timer.
But the timer comes in way more slowly
than one second, so the countdown
timer is off. The app should be
reworked to always update the
countdown timer based on the current
time, and not count down based on the
timer messages themselves. (In other
words, when the one second message
comes in, always assume that
additional time has gone by and
calculate the remaining time by
subtracting from the target time. This
is what happens when you restart the
app -- it figures out the target time
and the current time, subtracts one
from the other, and updates the
onscreen timer. Well, this is how it
should always do it.)
If someone understand what exactly we need, please tell me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSTimers 永远不应该被用来实际计时。它们依赖于运行循环,因此可能会受到运行时间较长的代码的干扰。
您应该在
applicationWillResignActive:
中停止计时器,并在applicationDidBecomeActive:
中恢复(实际上,创建另一个计时器)。要计算日期,您需要类似以下内容:
NSTimers should never be used to actually keep time. They are dependent on the run loop and therefore can be interfered with by code that takes a long time to run.
You should stop the timer in
applicationWillResignActive:
and resume (actually, create another timer) inapplicationDidBecomeActive:
.To calculate the dates you need something like:
使用纪元时间。 Epoch 时间是自 1970 年 1 月 1 日以来的秒数。
当程序启动时,保存当前的 Epoch 时间
,然后当您更新计时器时,
会告诉您自
start
以来已经过去了多少秒。Use epoch time. Epoch time is the number of seconds since Janury 1st, 1970.
When the program starts, save the current epoch time
And then when you update your timer,
Will tell you how many seconds have passed since
start
.