I have compiled the following code and there are no apparent runtime errors; however, the display freezes at 00:00:01 when I run it. It works if I only display the seconds attribute. Does anyone see an apparent oversight that I have missed in this code? I know there is a potential memory leak with the start button, but I will fix that eventually.
Thanks in advance.
#import "StopwatchViewController.h"
@implementation StopwatchViewController
- (IBAction)start{
//creates and fires timer every second
myTimer = [[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES]retain];
}
- (IBAction)stop{
[myTimer invalidate];
myTimer = nil;
}
- (IBAction)reset{
[myTimer invalidate];
time.text = @"00:00:00";
}
(void)showTime{
int currentTime = [time.text intValue];
int new = currentTime +1;
int secs = new;
int mins = (secs/60) % 60;
int hours = (mins/60);
time.text = [NSString stringWithFormat:@"%.2d:%.2d:%.2d",hours, mins, secs];
}
You’re getting 0 from
because the string that’s in
text:can’t be converted to an
int, so every time the timer fires, you add 1 to 0 and get 1, which you then display. The math would be inaccurate anyways, because minutes and seconds are “base-60″* — you’d need to do the reverse of the math you perform for separating hours/minutes/seconds, in order to get the total seconds again. You could just makecurrentTimean ivar, and keep the total number of seconds in it.*That’s not really what it’s called; I’m sure there’s a specific word for it.