Running a Method After A Delay on iPhone or Mac

In nearly every programming language there is a way to delay a method call. Objective-C is no different. They have built in a few simple methods to achieve this. We are going take a look at one of these methods today, all which reside in NSObject. This means any class you create will have the ability to call these methods. The method we are going to take a gander at is - (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay, got the love the Objective-C method names.

This method is pretty self explanatory thanks to the super long name. Basically, we are going to run a method and pass in the object as the parameter for the method after a certain amount of time (in seconds). Okay, imagine we have built an application which has a label that we want to change the text of after 5 seconds, why? I don’t know, if the label keeps the same text for more than 5 seconds it will self destruct, anyway I digress. So, we create a method to change the text to something like the following:

(void)changeText:(NSString *)text
{
  myLabel.text = text;
}

The new method is about as simple as it gets, it changes the label’s text to the passed in value. Now, in order to call this on a delay we need to use our aforementioned method, - (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay. In order to call our change text method with this it would look something like below.

[self performSelector:@selector(changeText:) withObject:@"Hello" afterDelay:5];

This pretty much covers it. One note is that say you have a method that doesn’t take a parameter like the one below.

(void)changeText
{
  myLabel.text = @"Hello";
}

Then if you want to call the method you pass in nil for the withObject argument, like the following:

[self performSelector:@selector(changeText) withObject:nil afterDelay:5];

Well that pretty much sums it up. You should now be able to call code after a delay. If you have any questions feel free to leave a comment or head on over to the forums.