Friday, December 28, 2007

Cocoa: Timed methods

Sometimes one wants to run a job a regular or scheduled times. One option would be to start a loop that runs until some abort condition is reached and that sleeps after the job is done. This is easily done, but has the big disadvantage to block the GUI while it is sleeping.
A better alternative is to set up a timer that calls you back from time to time. Cocoa offers the NSTimer class for this. It offers a wealth of methods to set up the timer and insert it into the RunLoop. The timer will then send from time to time a message to a method of your app that does the job.
It is actually easy to create the job. First you need to decide which method will be notified. In our example here it is - (void) runIt (with no arguments).
The code to set up the timer could then look like this:

NSTimer *timer;
timer = [NSTimer scheduledTimerWithTimeInterval:10.0
  selector: @selector(runIt)
  repeats: YES];

So this one schedules the execution of the runIt method of the same class the timer is created in, to repeat every 10 seconds.
To cancel the timer again, one just has to send it an invalidate method:
[timer invalidate]

I was first experimenting with scheduledTimerWithTimeInterval:invocation:repeats: but for whatever reason it did not work, even if the timer said it is valid. But the above works well for me and is even easier.

No comments: