简体   繁体   English

在iOS中实现计时器的方法

[英]Ways of implementing timer in iOS

What are some of the better/best ways of implementing a countdown timer in iOS? 在iOS中实现倒数计时器的更好/最好的方法有哪些?

I've done some digging and tried using NSTimers (1 sec timer) but some people suggest that's not a good way because its not very accurate!!! 我做了一些挖掘工作,并尝试使用NSTimers(1秒计时器),但是有人建议这不是一个好方法,因为它不是很准确! Others claim it wastes battery, since its always going to be on in the background till the time elapses. 其他人则声称它浪费了电池,因为它总是一直在后台运行,直到时间流逝。 I was thinking I could create a multiple scheduled NSTimer so it won't loose sync. 我当时想我可以创建多个计划的NSTimer,这样它就不会失去同步。 Some suggest I should record the actual timestamp at the beginning and somehow make use of the built-in clock and use that to update the timer countdown.... except I can't seem to figure out how to do that. 有人建议我应该在开始时记录实际的时间戳,并以某种方式利用内置时钟并使用它来更新计时器的倒计时...。不过我似乎无法弄清楚该如何做。 Any ideas? 有任何想法吗? How are you implementing it? 您如何实施?

Any time you are implementing a timer, the best option is always to record your start time. 每当您实施计时器时,最好的选择总是记录您的开始时间。 Then, whenever you update your interface, simply take the difference of the current time and your start time. 然后,每当您更新界面时,只需取当前时间与开始时间之差即可。 You can then use NSTimers to trigger updates of the interface at certain periods. 然后,您可以使用NSTimers在特定时间触发接口更新。

Indeed, NSTimer s are not very accurate. 确实, NSTimer不太准确。 So you should typically not simply multiply the time-interval you specified with the fire-count, but instead use some sort of time-stamp (eg a stored NSDate should work fine for your needs). 因此,通常您不应该简单地将指定的时间间隔与触发计数相乘,而应使用某种时间戳(例如,存储的NSDate应该可以很好地满足您的需求)。

Regarding the battery drain, I strongly doubt that a timer with an interval in the the frequency domain of ~1 Hz has any measurable effect. 关于电池消耗,我强烈怀疑在频域中间隔约为1 Hz的计时器是否具有可测量的效果。 And if I'm not completely mistaken, when your application enters the background, all timers will be paused and rescheduled with their respective fire-date, when the app re-enters to the foreground — so no harm here, either. 而且,如果我没有完全弄错,当您的应用程序进入后台时,当应用程序重新进入前台时,所有计时器都将暂停并重新安排各自的触发日期,因此在这里也没有害处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM