Reputation: 111
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
Upvotes: 0
Views: 1292
Reputation: 1
timeInterval will increase, like 1,2,3,4,5, etc.
totalTimeInterval = totalTimeInterval + timeInterval -> 0 = 0 + 1
Next time we call updateTimer function totalTimeInterval will be 1 = 1 + 2, so totalTimeInterval will be 3.
So if we display totalTimeInterval, seconds will be 1 , 3 , 6 , ....etc .
First you will need NSTimeInterval totalTimeInterval and NSTimeInterval timeInterval variable in class level
updateTimer method you'll need to replace following code.
timeInterval = [currentDate timeIntervalSinceDate:startDate]; timeInterval += totalTimeInterval; NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
and then onStopPressed method and following code.
totalTimeInterval = timeInterval;
Thanks.
Upvotes: 0
Reputation: 8564
In above code you are storing the time elapsed during start-stop action. To do this you will need NSTimeInterval totalTimeInterval
variable in at class level. Initially or when reset button is pressed its value will be set to 0. In updateTimer
method you will need to replace following code.
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
totalTimeInterval += timeInterval;
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:totalTimeInterval ];
Thanks,
Upvotes: 1