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 (开发者_Python百科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 :
A timer is not a real-time mechanism; it fires only when one of the run loop modes to which the timer has been added is running and able to check if the timer’s firing time has passed. Because of the various input sources a typical run loop manages, the effective resolution of the time interval for a timer is limited to on the order of 50-100 milliseconds. If a timer’s firing time occurs during a long callout or while the run loop is in a mode that is not monitoring the timer, the timer does not fire until the next time the run loop checks the timer. Therefore, the actual time at which the timer fires potentially can be a significant period of time after the scheduled firing time.
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.
2010-10-27 11:16:49.266 MutliTableTest[24726:207] Calculated: 9.988000000000
2010-10-27 11:16:49.267 MutliTableTest[24726:207] Measured : 10.000055888000
2010-10-27 11:16:59.266 MutliTableTest[24726:207] Calculated: 9.986000000000
2010-10-27 11:16:59.267 MutliTableTest[24726:207] Measured : 9.999898500000
2010-10-27 11:17:09.608 MutliTableTest[24726:207] Calculated: 8.091000000000
2010-10-27 11:17:09.609 MutliTableTest[24726:207] Measured : 10.341779530000
2010-10-27 11:17:19.266 MutliTableTest[24726:207] Calculated: 1.966000000000
2010-10-27 11:17:19.267 MutliTableTest[24726:207] Measured : 9.658319274000
2010-10-27 11:17:29.266 MutliTableTest[24726:207] Calculated: 9.991000000000
2010-10-27 11:17:29.267 MutliTableTest[24726:207] Measured : 9.999891531000
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
精彩评论