Saturday 7 February 2009

Timers

During the development of the Game Of Life, I was wondering how I could capture mouse events and still running the application.

In a first , naive , implementation I had a for(..) loop which called the oneIteration method.

Of course this wasn't very intelligent :-). I had no chance to interrupt the program until the loop was finished.
Then I stumbled on 2 classes: NSAnimation and NSTimer.
In my case NSTimer was sufficient, I only needed a timer which would fire every second to launch the oneIteration method.

The important thing is that a timer will not interrupt a function in the middle of its execution (god forbid what for side effects that could have).

So my creation of a Timer is as follows :

[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(oneIteration)
userInfo:nil

repeats:YES]

In human language it means that I've created a repeatable timer with an interval of 1 second and that will send the message oneIteration to self.

Once a timer is created , it will automatically fire. If you want to force the timer to fire , just send the message fire to it.

2 notes here :

1. You cannot suspend a timer, you can only stop it (by sending invalidate to it).
2. Don't send release to an invalidated timer, I got multiple crashes in my application

So if you want to chance the interval of a Timer , then you have to invalidate the old one and recreate a new one

No comments:

Post a Comment