Hello I have a stopwatch in my app.
I have a start, stop and reset button with the stopwatch.
The stop and reset buttons work
The start works sort of.
When a user first clicks on the start button it starts the stopwatch. If they click on the stop button then click back on the start button, it starts the stopwatch all over again.
What am I missing (code listed below)?
.h
IBOutlet UILabel *stopWatchLabel;
NSTimer *stopWatchTimer; // Store the timer that fires after a certain time
NSDate *startDate; // Stores the date of the click on the start button
@property (nonatomic, retain) IBOutlet UILabel *stopWatchLabel;
- (IBAction)onStartPressed;
- (IBAction)onStopPressed;
- (IBAction)onResetPressed;
- (void)updateTimer
.m
- (void)updateTimer{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss:SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
stopWatchLabel.text = timeString;
}
- (IBAction)onStartPressed {
startDate = [NSDate date];
// Create the stop watch timer that fires every 10 ms
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:@selector(updateTimer)
userInfo:nil
repeats:YES];
}
- (IBAction)onStopPressed {
[stopWatchTimer invalidate];
stopWatchTimer = nil;
[self updateTimer];
}
- (IBAction)onResetPressed {
stopWatchLabel.text = @"00:00:00:000";
}
Any help would be great.
Cheers
In above code you are storing the time elapsed during start-stop action. To do this you will need
NSTimeInterval totalTimeIntervalvariable in at class level. Initially or when reset button is pressed its value will be set to 0. InupdateTimermethod you will need to replace following code.Thanks,