My utility app will have 20 individual timers, laid out like this:
- (void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
stopWatchLabel.text = timeString;
[dateFormatter release];
}
- (IBAction)onStartPressed:(id)sender {
startDate = [[NSDate date]retain];
// Create the stop watch timer that fires every 1 s
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(updateTimer)
userInfo:nil
repeats:YES];
}
- (IBAction)onStopPressed:(id)sender {
[stopWatchTimer invalidate];
stopWatchTimer = nil;
[self updateTimer];
}
I would like to add all of the time intervals together, and display them as a string. I thought this would be easy, but I just can't get it. I need to sum the NSTimeIntervals, right?
Several approaches you could take. One is to create a timer class that that can be queried for its state (running, stopped, not started, ...) and for its current time interval. Add all of the timers to a collections such as an
NSMutableArray
. You could then iterate over all the timers in the collection, and for those that are stopped, get its time interval, and sum them together. The partial header for aMyTimer
class:Declare your array:
Add each timer to the array:
When appropriate, iterate over the collection of timers and sum the time intervals for the
Stopped
timers: