Archive for September 5th, 2009


Tip: CACurrentMediaTime

Here’s a subtlety of time-based computation that you probably aren’t (well, we weren’t) aware of on the iPhone: Chances are that you’re using CFAbsoluteTimeGetCurrent or its wrappers like [NSDate timeIntervalSinceReferenceDate] for your time snaps … and that is actually not good practice!

See, those functions return clock time. Clock time is synchronized, unpredictably, with the network time signal. So if you’re looking for a reliable timer for in-application events … that’s not it! Discussion here if you’re on the dev forums, but the solution is simple: Use instead the Core Animation function CACurrentMediaTime, which we hadn’t noticed before but apparently takes care of the tricky bits in converting mach_absolute_time() into seconds.

So if you’ve noticed any weirdness in your timing, or if you have something that could be hopelessly confused by clock synchronization turning your “elapsed” time into a negative value, or the like … best to make that switch now!

h/t: 71^2!