Show Menu

Do you have a job opening?

Submit your 30 day Job Listing for FREE

A great and insightful introduction to the Objective-C: NSTimer Class.

UPDATE 15/12/2014:
If you’re wanting to see how to use NSTimer with Swift then checkout this: Swift Timer tutorial.

If you would like to see an example of NSTimer in use, please see: Create falling objects in your iOS Application using NSTimer

“You use the Objective-C NSTimer class to create timer objects or, more simply, timers. A timer waits until a certain time interval has elapsed and then fires, sending a specified message to a target object. For example, you could create an NSTimer object that sends a message to a window, telling it to update itself after a certain time interval.” Apple

Firstly I’d like to draw your attention to the Cocoa/CF documentation (which is always a great first port of call). The Apple docs have a section at the top of each reference article called “Companion Guides”, which lists guides for the topic being documented (if any exist). For example, with NSTimer, the documentation lists two companion guides:

Timer Programming Topics for Cocoa
Threading Programming Guide

The Timer Programming Topics article is likely to be the most useful, whilst threading topics are related but not the most directly related to the class being documented. If you take a look at the Timer Programming Topics article, it’s divided into two parts:

– Timers
– Using Timers

For articles that take this format, there is often an overview of the class and what it’s used for, and then some sample code on how to use it, in this case in the “Using Timers” section. There are sections on “Creating and Scheduling a Timer”, “Stopping a Timer” and “Memory Management”. From the article, creating a scheduled, non-repeating timer can be done something like this:

[NSTimer scheduledTimerWithTimeInterval:2.0

This will create a timer that is fired after 2.0 seconds and calls targetMethod: on self with one argument, which is a pointer to the NSTimer instance.

If you then want to look in more detail at the method you can refer back to the docs for more information, but there is explanation around the code too.

If you want to stop a timer that is one which repeats, (or stop a non-repeating timer before it fires) then you need to keep a pointer to the NSTimer instance that was created; often this will need to be an instance variable so that you can refer to it in another method. You can then call invalidate on the NSTimer instance:

[myTimer invalidate];
myTimer = nil;

It’s also good practice to nil out the instance variable (for example if your method that invalidates the timer is called more than once and the instance variable hasn’t been set to nil and the NSTimer instance has been deallocated, it will throw an exception).

Note also the point on Memory Management at the bottom of the article:

Because the run loop maintains the timer, from the perspective of memory management there’s typically no need to keep a reference to a timer after you’ve scheduled it. Since the timer is passed as an argument when you specify its method as a selector, you can invalidate a repeating timer when appropriate within that method. In many situations, however, you also want the option of invalidating the timer—perhaps even before it starts. In this case, you do need to keep a reference to the timer, so that you can send it an invalidate message whenever appropriate. If you create an unscheduled timer (see “Unscheduled Timers”), then you must maintain a strong reference to the timer (in a reference-counted environment, you retain it) so that it is not deallocated before you use it.

Scheduled Timer & Using Selector

NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
                      target: self
                      userInfo: nil repeats:NO];

if you set repeats to NO, the timer will wait 2 seconds before running the selector and after that it will stop;
if repeat: YES, the timer will start immediately and will repeat calling the selector every 2 seconds;
to stop the timer you call the timer’s -invalidate method: [t invalidate];
As a side note, instead of using a timer that doesn’t repeat and calls the selector after a specified interval, you could use a simple statement like this:

[self performSelector:@selector(onTick:) withObject:nil afterDelay:2.0];

This will have the same effect as the sample code above; but if you want to call the selector every nth time, you use the timer with repeats:YES;

Self-Scheduled Timer

NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
                              interval: 1
                              target: self
                              userInfo:nil repeats:YES];

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
[t release];

This will create a timer that will start itself on a custom date specified by you (in this case, after a minute), and repeats itself every one second.

Unscheduled Timer & Using Invocation

NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:@selector(onTick:)];

NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
and after that, you start the timer manually whenever you need like this:

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: t forMode: NSDefaultRunLoopMode];

And as a note, onTick: method looks like this:

-(void)onTick:(NSTimer *)timer {
   //do something

I hope you find this Objective-C tutorial beneficial, just to mention: This post is an amalgamation of answers from stack overflow users. Mostly: Woofy & Alex Rozanski .

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly

Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.

Written by:

I work in the shadows. You can thank me by being a good soul.