iOS: Timer countdown implementation tutorial (including source code)

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
	target:self
	selector:@selector(updateLabel:)
	userInfo:nil
	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];
	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{
	if(timer){
		[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.

One thought on “iOS: Timer countdown implementation tutorial (including source code)

Give Your feedback: