Reputation: 18558
I'm diving into iOS development and I'm trying to create a count up timer in one of my views. I have the NSTimer
code figured out to call a selector once every 0.04 seconds that updates the UILabel
. Where I'm having trouble is with the formatting of the current time (starting initially at 00:00). I figured the best way to do this was using the NSDate
class, and related classes (NSDateFormatter
, NSDateComponents
, etc.), but the manipulating of the dates and formats is really confusing me and the code is getting unwieldy quickly. I was hoping there are some SO users that are comfortable using the NSDate
class that could help me figure out a simple way to calculate the current time for a count up timer and convert it to an NString
with the format 'seconds:milliseconds'.
I'd be happy to post my initial attempt at the NSDate
code if requested, but I won't initially because it's really of no use and embarrassing :)
Upvotes: 0
Views: 2239
Reputation: 170829
If you just want to display time elapsed since you started your timer you can store starting date somewhere (say, startDate variable) and calculate time interval using current date. Something like the following should work:
NSTimeInterval passed = [[NSDate date] timeIntervalSinceDate: startDate];
double intPart;
double fract = modf(passed, &intPart);
label.text = [NSString stringWithFormat:@"%d:%.2f", (int)intPart, fract];
Upvotes: 3