My question is quiet simple (I think). I have a class that implements a simple chronometer (using some integers and NSTimer). I would like to close my app (so enter in background mode) but I would like my chronometer still continue to count. How can I manage that ?
Thanks a lot !
Save the time which was present when you started the timer. Something like
self.timerStartDate = [NSDate date];. Calling NSTimer once a second and increment a integer will give you very inaccurate results.From the NSTimer Class Reference :
If you use the approach with saving the startTime your Timer even “runs” if the program is not running
EDIT:
yes. it is wrong to use a timer to count time.
I just wrote a little test case. An app with a simple tableview with 12 rows. Two timers, one fired every millisecond, the other is fired every 10 seconds.
In the first timer I add 1 to an Integer, in the second one I print the result of the first timer and the time which passed since the last time I printed, measured with mach_absolute_time().
Look at the differences, the first measurements are quite ok, but if I start scrolling in that simple UITableView, which runs in the simulator on my powerful mac you get a big difference.
So don’t use NSTimer, use a NSDate and get the difference between current time and the startTime with something like
NSTimeInterval ti = [[NSDate date] timeIntervalSinceDate:self.startDate];But I wonder why you need a differenct timeStamp every millisecond