iPhone: Delay Calling A Function (Passing a message)

Some posts I write are to cover topics which I have needed before and find myself scrabbling through old code or search engine histories to find. This is one such post and concerns how to call a function asynchronously.

In iOS it is occasionally useful to be able to call functions (technically send a message to a thing) after the current function you are in has completed. The reason for this most likely is that you need some unexposed part of the operating system to complete before performing calculations on aspects of the UI.

This is indeed my exact situation – I’m not sure of the specifics but in the viewDidLoad method of a view controller certain parts of the UI haven’t been laid out properly. To this end I have an “arrange my stuff” function which rearranges the layout based around the location of other items.

In order to get this to work correctly it has to be called after viewDidLoad but not during. Therefore we need to use an asynchronous call which we do like this:

[self performSelector:@selector(myDelayedFunctionName) withObject:self afterDelay:0.1];

This causes the method to be called on the view controller with a delay of 0.1 seconds (which is unnoticeable from the users point of view).

Posted in iOS, Mobile Tagged with: , , ,

Leave a Reply