iOS: Timer countdown implementation tutorial (including source code)

29 12 2012

This lesson shows how to build timed periodic updates in iOS app using NSTimer. In my example I update timer value in text label. GUI consists of one label and one button. Button press starts the timer countdown.

Timer app GUI captions

Timer app GUI captions

1. Create NSTimer instance

I use timer variable that holds reference to NSTimer object. Timer is then handled using iOS notifications in ViewController:

timer = [NSTimer scheduledTimerWithTimeInterval:1.0
	repeats:YES ];

Here the interval is set (in seconds) and the repeats flag. Target is set to self (ViewController) to the updateLabel: method. Timer is started instantly after initialization.

2. Define updater method

The updateLabel:sender will be called by iOS notification every time, when timer interval will pass. Here you can put custom code that is required by your app logic.

My logic simply increases counter value and updates text label with the new counter value. I also check if counter does not exceed MAX_VALUE. if it does, I invalidate the timer (see next point to see how to invalidate timer).

- (void)updateLabel:(id)sender{
	if(counterValue >= MAX_VALUE){
		[self killTimer];
	self.counterLabel.text = [NSString stringWithFormat:@"%d", counterValue];

3. How to stop repeatable timer?

If you set your timer to repeatable, it will be repeating infinitely. To stop it you need to invalidate it. I also set it to nil. I use killTimer: method that handles it:

- (void)killTimer{
		[timer invalidate];
		timer = nil;

Be careful: invalidating timer that was already invalidated will cause application to crash! This is why I check if timer is not nil before invalidating it.

4. Download my source code

If the tutorial is not enough for you, here is the source code for header and implementation file.

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!



One response

12 10 2013


Give Your feedback:

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: