Creating an iOS Timer

v0idless picture v0idless · Jul 15, 2011 · Viewed 39.6k times · Source

I am trying to create a "stop watch" type functionality. I have one label (to display the elapsed time) and two buttons (start and stop the timer). The start and stop buttons call the startTimer and stopTimer functions respectively. Every second the timer fires and calls the increaseTimerCount function. I also have an ivar timerCount which holds on to the elapsed time in seconds.

- (void)increaseTimerCount
{
    timerCountLabel.text = [NSString stringWithFormat:@"%d", timerCount++];
}

- (IBAction)startTimer
{
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(increaseTimerCount) userInfo:nil repeats:YES];

}

- (IBAction)stopTimer
{
    [timer invalidate];
    [timer release];
}

The problem is that there seems to be a delay when the start button is pressed (which I am assuming is due to reinitializing the timer each time startTimer is called). Is there any way to just pause and resume the timer without invalidating it and recreating it? or a better/alternate way of doing this?

Thanks.

Answer

vladz picture vladz · Jul 22, 2012

A bit dated but if someone is still interested...

don't "stop" the timer, but stop incrementing during pause, e.g.

- (void)increaseTimerCount
{
   if (!self.paused){
      timerCount++
   }

   timerCountLabel.text = [NSString stringWithFormat:@"%d", timerCount];
}