Friday, October 14, 2011

How to schedule the execution of a function using NSTimer

The NSTimer class
The NSTimer class can be used to schedule the execution of a function in a program for MacOS X, iPhone /  iOs.
You can execute a function for any object, pass some user defined datas, and optionally you can repeat the scheduled execution automagically.

The target function
First, you have to write the target function.
This function must have a NSTimer* parameter because you can use it with multiple timers.
In this exemple, the target function called timerEnd stops the animation of a UIActivityIndicatorView called indicator then posts a notification if the user have entered some text in a UITextField named textNom :

-(void) timerEnd: (NSTimer *) theTimer { 
    [indicator stopAnimating]; 
    if ([textNom.text length] > 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"My Notification"  
                                                            object:textNom.text]; 
    } 
    textNom.text = @""; 
} 

Scheduling the timer
Once you have your target function ready, you can schedule the execution using the +NSTimer:scheduledTimerWithTimeInterval class function.
In the following example, the timer execute the [self timerEnd] message after 5 seconds :

[NSTimer scheduledTimerWithTimeInterval: 5.0  
                                 target: self  
                               selector: @selector(timerEnd:)  
                               userInfo: nil  
                                repeats: NO];





Notes on NSTimer
Never forget that NSTimer relies on the run loop. It means :

  • You must have a run loop. If you write a MacOS X console application, you must write it yourself. If you write a library or a Framework, you must document the fact that a run loop is mandatory.
  • Run loops retain timers. So you can release your timers once scheduled.
  • It's not real time. The run loop execute the timers once it have checked that the timer time have been passed. Hence in the preceding example the "after 5 seconds" and not "in 5 seconds".
  • the +NSTimer:scheduleTimer* functions creates the timer and pushes it in the run loop. If you only want to create the timer use +NSTimer:timerWithTimeInterval functions then use -NSRunLoop:addTimer to push the timer (you can use +NSRunLoop:currentRunLoop to get the current run loop).

No comments: