Ever been in a situation where you need to wait for an asynchronous task to complete. This is a rare case but sometimes you need to do this. I used this techinque in my previous post on how to extract the user-agent string from a UIWebView. Check it out for a more complete sample.

The trick is to use NSRunLoop which allows you to access the applications run loop. runMode:beforeDate allows you to execute one loop at the time so calling this in a while loop you can wait for something to complete and then move on. Here’s a sample:

int i = 0;
while (i < 10) 
{
	// This executes another run loop. 
	[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
 
	i++;
}

This will execute/wait 10 run loops before moving on. Obviously this is a retarded sample because it has no real use. What you might want to do is wait for a UIWebView to execute a request or for a NSMutableURLRequest to complete. Yes, NSURLRequest has a synchronous mode but that doesn’t allow for delegate methods to execute. If you don’t understand why you would won’t to do this, DON’T DO IT!

Related posts