iPhone delayed messaging.
I’ve been developing an iPhone application for a while now. Hopefully in the next few weeks we’ll have gotten enough done to actually post some public photos, and some more information. But one thing that I was originally having trouble with (beyond the oddities that come with the iPhone dev kit itself) was how to make something happen after x number of seconds.
If you’ve looked into doing this, you might have thought that using a timer (likely an NSTimer) would be the best idea, and there are plenty of cases when this is true, but I have found that all of my needs have been met by delayed messaging.
How delayed messaging works is as follows: (I’m going to assume your classes inherit from NSObject, if they don’t then the following will not work, though they should all inherit from NSObject if you are doing iPhone dev work).
NSObject comes with the following function:
- (void) performSelector
:(SEL) aSelector
withObject :(id) anArgument
afterDelay :(NSTimeInterval) delay;
This means you can send another object a call, with any valid NSObject in scope, after delay seconds. The opposite of this is the cancel, which can be called whether or not there is a performSelector call waiting to occur.
+ (void) cancelPreviousPerformRequestsWithTarget
:(id) aTarget
selector :(SEL) aSelector
object :(id) anArgument;
The implications of these two calls are amazing.
In my own app I need to find out where a user is, but I don’t want to leave the GPS on if the user isn’t moving. Whenever I get new data about the users location I call:
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(stopFindingUser) object:nil];
[self performSelector:@selector(stopFindingUser)
withObject:nil afterDelay:5];
The above two lines of code do the following. Line one says that if there are any pending calls to stopFindingUser, cancel those calls. The second line says that in 5 seconds stopFindingUser will be called.
Delayed messaging is pretty simple, but incredibly powerful.