Ryan IRL

Intro to Using NSTimer

I’ve been wanting to start writing some simple Cocoa tutorials lately, and I’m going to start with something easy, yet potentially frustrating. Timers. NSTimer is a great class for triggering timed events. Even though timed events aren’t really hard to implement, they can be tricky to do right. For starters, you need a run loop, a timer, a way to keep track of time elapsed since last cycle (delta time), and probably some thread management (if you don’t want other processes to be blocked). Why not spend that extra time writing something that makes your application better, right?

There are pretty much two types of timers with two styles of setting the callback. There is the scheduled timer which adds the timer to a default run loop which will start the timer automatically, and there is the standard timer which must be added to an NSRunLoop (which I won’t cover here). Both types have a variation which can be initialized with an NSInvocation class, which is really a fancier way of setting the callback (target selector). So let’s start with the most basic example of how you would initialize, and use NSTimer.

// Assume this is in a controller class, or somewhere equally useful
 
- (NSTimer)createTimer {
    // Create a managed timer (don't need to add to the run loop!)
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5
        target:self selector:@selector(targetMethod:)
        userInfo:nil repeats:YES];
 
    return self.timer;
}
 
- (void)targetMethod:(NSTimer*)timer {
    NSLog(@"targetMethod called!");
}

Now that example will fire the timer as soon as you call createTimer, and trigger the targetMethod until you quit the application or call [self.timer invalidate];. It should be noted that with this method the target HAS to take the timer as an argument.

What if you KNOW you won’t need a repeating timer though? There must be an easier way. Well, there is. Every NSObject class has the method performSelector:withObject:afterDelay: which makes life even easier.

More complete examples on NSTimer can be found in the reference library.

This entry was written by Ryan Leland, posted on January 12, 2010 at 11:53 pm, filed under Cocoa. Leave a comment or view the discussion at the permalink.