简体   繁体   中英

Ways of implementing timer in iOS

What are some of the better/best ways of implementing a countdown timer in 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!!! 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. 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.

Indeed, NSTimer s are not very accurate. 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).

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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