Under the Bridge

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!

2
  • Jay

    Hard to tell what year this was published, but there two of the links are bad now in 2013.

    • http://twitter.com/trollwerks Alex Curylo

      Yeah, I guess I should look for a way to tell this theme to display the year. In the meantime, the “2009/09/05″ in the URL is your clue. Some level of netrot is to be expected :)