While NSTimer
will kind of work, it's not really made for creating stop watches or the like. You can't rely on it firing every second, so you'll still need to use a NSDate
object and something like timeIntervalSinceDate
to calculate the value to display for the timer each time it fires. That way, your stop watch can catch up if it should happen to not fire for one or more seconds.
NSTimer events are processed by the main run loop, and if the main run loop is busy, the events aren't fired.
I like the background thread idea better. However, you don't need the recursion to make it work.
Simply create a custom Timer class with a start, calcTime, (and perhaps stop, reset, and resume). When you call start, the object should simply get the current date/time (NSDate) and store it. When you call calcTime, simply get the current date/time again, calculate the time elapsed using timeIntervalSinceDate
, and either return the value or set properties that you can read.
In a background thread, simply keep calling the calcTime
method and update the UI via dispatch_async(dispatch_get_main_que)()
, then sleep for maybe 100 milliseconds between calls. You can check a Boolean global variable to see if you should keep running.
A background thread still may get bogged down if the processor is pegged, however, that's less likely to happen than the main run loop being busy, which is responsible for so much.
I've created a stop watch app, and this is the method I used, after deciding NSTimer wasn't viable.