The first function is called when the startButton is pressed. If the text of the button
is Start, then we want to disable the resetButton, change the startButton's text to Stop
mark the startTime, and instantiate the timer callback. If the text of the startButton is
not Start, then we want to enable the resetButton, disable the startButton, and invalidate
the timer callback funtion.
The second function handles the resetButton. If the resetButton's been pressed, the timeLabel
is reset to 00:00:00.0, the startButton text is set to Start and enabled, and the resetButton
Finally, we have a function to handle the timer callback. This method is called when
the timer fires - in this case, every 0.1 seconds.
- (void) updateStopWatchLabel
nowTime = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval interval = nowTime - startTime;
int seconds = (int)interval;
int tenths = (int)((interval - seconds) * 10);
[timeLabel setText:[NSString stringWithFormat:@"%02d:%02d:%02d.%1d",(seconds/3600)%24,(seconds/60)%60, seconds%60, tenths]];
In the simulator and on the iPhone, the application looks like this:
In many of the sample code I ran across on the web, people would use an integer to keep track of the elapsed time.
Don't. NSTimeInterval is a quick way to grab the elapsed time in milliseconds from a fixed reference point. It's
fast, neat, and works well. It would be easy to only have one function handle all the button UI. I kept it in two
functions just to make it clearer, I hope. Enjoy.