开发者

iOS: recreating countdown timers after clock change?

开发者 https://www.devze.com 2023-03-30 02:04 出处:网络
I\'m working on an iOS app that uses an NSTimer for a countdown. This is prone to user tampering: if, for example, the user switches out of the app, closes the app manually, changes the device clock,

I'm working on an iOS app that uses an NSTimer for a countdown. This is prone to user tampering: if, for example, the user switches out of the app, closes the app manually, changes the device clock, and comes back in, the timer will have to be recreated. Another scenario: the user locks the device, it goes into low-power mode (which requires timers to be recreated), and the clock auto-sets before the game is opened again. If that happens, I won't have an accurate way of determining how much time has passed since the app was closed, since the device clock has changed.

开发者_C百科Tl;dr: countdown timers sometimes have to be recreated after a device clock change. How is this problem usually handled?


Any time you're relying on the system clock for accurate timing you're going to have troubles, even if the user isn't deliberately tampering with the clock. Typically clock drift is corrected by slightly increasing or decreasing the length of a second to allow the clock to drift back into alignment over a period of minutes. If you need accurate timing, you can either use something like mach_absolute_time() which is related to the system uptime rather than the system clock, or you can use Grand Central Dispatch. The dispatch_after() function takes a dispatch_time_t which can either be expressed using wall time (e.g. system clock) or as an offset against DISPATCH_TIME_NOW (which ignores wall clock).


For future reference, in regard to different systems of timekeeping in OSX (and consequently iOS):

One way to measure the speed of any operation, including launch times, is to use system routines to get the current time at the beginning and end of the operation. Once you have the two time values, you can take the difference and log the results.

The advantage of this technique is that it lets you measure the duration of specific blocks of code. Mac OS X includes several different ways to get the current time:

  • mach_absolute_time reads the CPU time base register and is the basis for other time measurement functions.
  • The Core Services UpTime function provides nanosecond resolution for time measurements.
  • The BSD gettimeofday function (declared in <sys/time.h>) provides
    microsecond resolution. (Note, this function incurs some overhead but is still accurate for most uses.)
  • In Cocoa, you can create an NSDate object with the current time at the beginning of the operation and then use the
    timeIntervalSinceDate: method to get the time difference.

Source: Launch Time Performance Guidelines, "Gathering Launch Time Metrics".

0

精彩评论

暂无评论...
验证码 换一张
取 消