Sunday, February 22, 2009

Using timers on the iPhone

The iPhone's threading model is based on run loops. One way to execute code asynchronously is to add a timer to a run loop and put the asynchronous code in the selector given to the timer constructor:


[[NSRunLoop currentRunLoop] addTimer:[NSTimer timerWithTimeInterval:3 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO] forMode:NSDefaultRunLoopMode];

return character;
}

- (void)timerFired:(NSTimer *)timer {
ready = YES;
[self setNeedsDisplay];
}

It's just that easy. This is part of Core Foundation so no extra frameworks are needed. :) If it's not intuitive, the repeats parameter decides if it will run only once. In this case, I've used a timer to clear a graphics context after an interval which was used as a hint before the user has to draw a character on the screen.

0 comments:

Post a Comment