Here is my problem,
When I click on the start button the timer runs, when I click on the stop button it stops. However when I click back on the start button it goes back to zero. I would like the start button to continue where the timer stopped at.
.h
NSTimer *stopWatchTimer;
NSDate *startDate;
@property (nonatomic, retain) IBOutlet UILabel *stopWatchLabel;
- (IBAction)onStartPressed;
- (IBAction)onStopPressed;
- (IBAction)onResetPressed;
.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″;
}
Please help thank you
You have a problem dealing with state. One state would be that the start button is pushed, but the reset button has not been pushed before it. Another state is that the start button is pushed, and the reset button has been pushed before it. One thing you can do is create an iVar to keep track of this state. So use a BOOL like this:
First declare the iVar:
Initialize the value to NO.
Then do this
Now you need to set it back to NO, at some point, and that might be done in the start method:
By the way, if you make your NSDateFormatter in iVar, you don’t need to initialize it repeatedly. Movethe following lines to you inti code, or osmewhere it only runs once:
UPDATE
Try this: