I use NSTimer to count from a certain moment.
int totalSeconds;
int totalMinutes;
int totalHours;
If the totalSeconds are 60, totalMinuts become +1. Its very simple and should work.
For example i started the NSTimer together with the clock of my mac. (running on simulator).
When i look at the clock of my mac and the timer and compare the time the first 10-20 seconds its counting perfectly synchronous. After that it fluctuates or goes ahead 5 seconds or more.
So i output my timer and found this:
- 2012-10-24 14:45:44.002 xxApp driveTime: 0:0:44
- 2012-10-24 14:45:45.002 xxApp driveTime: 0:0:45
- 2012-10-24 14:45:45.813 xxApp driveTime: 0:0:46
- 2012-10-24 14:45:46.002 xxApp driveTime: 0:0:47
The milliseconds are timed at 002 as you see. But at the third row its 813. This happens very randomly and causes the fluctuations.
Is there a more stable way to count?
From the NSTimer documentation
If your goal is to compute the total time that has passed since your program has started running, this is quite easy. As soon as you want to begin keeping track of time, store
-[NSDate date]into a variable. Whenever you want to compute how much time has passed, call-[NSDate dateagain and do the following, assumingoriginalDateis a property where you stored the result of the first call to-[NSDate date]:runningTimewill be the total number of seconds that have elapsed since you started keeping track of time. In order to get the number of hours, minutes, seconds, and so on, anNSDateComponentsobject should be used.This mechanism will allow you to use a timer to update your total running time “just about once a second” without losing accuracy.