Friday, May 27, 2011

Show timer with seconds using NSTimer on iPhone and Objective C

I am currently developing an iPhone App using X-Code and Objective-C. I had to show a simple timer showing the elapsed number of seconds and minutes. I don’t know much about Objective-C, but from my past experience I knew this task can be easily accomplished using a Timer. The timer should be called every second, and a simple int variable will hold the seconds. The variable is incremented on every call of the timer.
This is how I the timer is defined:
NSTimer *mainTimer = [NSTimer scheduledTimerWithTimeInterval:1 
                  target:self 
                  selector:@selector(timerController) 
                  userInfo:nil 
                  repeats:YES];

Note that the timer is set to be activated every one second and the function that will be called every one second is named “timerController”.

In the “timerController” function I wrote the code that will increment the seconds variable as well as update a label on the screen. In order to update the label with the minutes and seconds I wrote a small function. The function gets seconds and returns a string of the format: “mm:ss” (for example, for input of 90 the function will return: “01:30”. Let’s see the function that returns the time:


- (NSString*)getTimeStr : (int) secondsElapsed {
  int seconds = secondsElapsed % 60;
  int minutes = secondsElapsed / 60;
  return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
}

And let’s have a look at the “timeController” function that use it:


- (void)timerController {
  seconds++;
  [[self timeLabel] setText:[self getTimeStr]];
}

The “timeLable” is a UILabel control that is connected with a label that is show on the iPhone screen.


1 comment:

  1. "int seconds" is hidden, you can see this on "timerController" :(

    ReplyDelete