NSTimer - Stopwatch

I am trying to create a stopwatch with HH: MM: SS, the code is as follows:

-(IBAction)startTimerButton;
{
    myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}


-(IBAction)stopTimerButton;
{
    [myTimer invalidate];
    myTimer = nil;
}


-(void)showActivity;
{
    int currentTime = [time.text intValue];
    int newTime = currentTime + 1;
    time.text = [NSString stringWithFormat:@"%.2i:%.2i:%.2i", newTime];
}

Although the output increases by 1 second, as expected, the output format is: XX: YY: ZZZZZZZZ, where XX is the second.

Any thoughts?

0
source share
1 answer

Your stringWithFormat asks for 3 integers, but you only pass one;)

Here is the code I used before to do what I think you are trying to do:

- (void)populateLabel:(UILabel *)label withTimeInterval:(NSTimeInterval)timeInterval {
    uint seconds = fabs(timeInterval);
    uint minutes = seconds / 60;
    uint hours = minutes / 60;

    seconds -= minutes * 60;
    minutes -= hours * 60;

    [label setText:[NSString stringWithFormat:@"%@%02uh:%02um:%02us", (timeInterval<0?@"-":@""), hours, minutes, seconds]];
}

To use it with a timer, do the following:

    ...
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
    ...

- (void)updateTimer:(NSTimer *)timer {
    currentTime += 1;
    [self populateLabel:myLabel withTimeInterval:time;
}

where currentTime is the NSTimeInterval that you want to count once per second.

+6
source

All Articles