简体   繁体   中英

iOS System Time Update Causes NSTimer/NSDate funkiness

I'm working on an app that has an event timer that times an event (duh!) that can last a long time.

I've done other apps with timers over a fairly extended time period and never come across this problem before.

Basically, what's happening is that when the app launches, I set an NSDate value with [NSDate date] . Then, I have a scheduled NSTimer object that fires regularly and checks how much time has elapsed by comparing the current [NSDate date] value against the original one.

As far as I know, that's the correct way to do this sort of thing, but please correct me if I have a faulty assumption in the above paragraph.

Anyway, when testing on my new iPad over the last few weeks, I've variously (and randomly) caught a few times where it appears that my system time is jumping around a good bit. In one instance, the time seems to have jumped 64 seconds! This meant that my timer label displayed '00:03' and then immediately displayed '01:08' (add a second correctly and then 64 incorrectly)!!! At other times, it has resulted in a negative event duration.

It's an intermittent occurrence, so I'm basically asking whether this could be:

  1. An iOS 5.1 bug
  2. Something to do with the hardware specific to the new iPad (never had this issue on iPad 1st Gen, 2nd Gen, several iPhone/iPod Touch versions, etc...)
  3. Bad Code (I'll admit this is possible, but it's not like the NSDate value ever becomes something other than an NSDate value, and I've checked every place in my project where this singleton value is set.

Has anyone had any similar experience? Can anyone help?

This is not a iOS device or OS version bug.

The NSDate API is not guaranteed to be consistent, or even monotonic, as you have found. It drifts (depending on temperature and such) and then gets corrected from either cellular or NTP sources, after which the date and time value can jump.

For a monotonic local timer, you can try the functions in mach_time.h . For a better absolute time reference, your app can try polling a network time source. Or you can tie your own time function to some combination of both.

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