Quote:
Originally Posted by Shades of Chaos
Hi
I am new to iphone development and am having trouble making a timer. My code so far is:
-(IBAction)startTimer  id)sender {
myTicker = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}
-(void)showActivity {
int currentTime =[time.text intValue];
int newTime = currentTime + 1;
time.text = [NSString stringWithFormat:@"%d", newTime];
}
This works for counting seconds, but I want to count the milliseconds. I have tried changing currentTime and newTime to floats, and intValue to floatValue but it stops working all together then.
Can someone please show me a way that I can modify this code to count milliseconds.
Thanks
|
NSTimers are somewhat limited. They only fire when your program visits the event loop and checks to see if a timer is ready to fire. According to the docs, timers have a minimum resolution of 50 to 100 ms (0.05 to 0.1 seconds) depending on how often your program visits the event loop.
If you want to do accurate time calculations, you should record your starting time and ending time as NSTimeInterval values, which are doubles, and not convert them to text. Something like this:
In your header:
Code:
NSTimeInterval startTime, endTime, elapsedTime;
To record the start time:
Code:
startTime = [NSDate timeIntervalSinceReferenceDate];
Then, when you want to calculate the amount of time that has elapsed:
Code:
endTime = [NSDate timeIntervalSinceReferenceDate];
elapsedTime = endTime - startTime;
elapsedTime will be in seconds and fractions of a second, and very accurate.
You can always convert elapsedTime to a string with something like this:
Code:
NSString* displayTime = [NSString stringWithFormat: @"%.3f", elapsedTime];
The "%.3f" above will display the time with 3 decimal places (milliseconds). Change the number before the "f" to change the number of decimal places.