Multithreading and Concurrency On The iPhone, the easy way

iPhone developers seem to treat concurrency as a dark art, secret knowledge that only a select few can handle. The forums are full of responses frightening people about the complexity of multithreading, when there’s generally a simple solution that solves the problem.
I don’t want to spend a lot of time talking about the low level goings on regarding concurrency, because frankly it’s extremely boring. All I’m interested in is making sure my UI doesn’t lock up when I make a webservice call, and I want a simple solution that will do this.
So in the spirit of getting shit working the quick and dirty way here’s a simple solution that I use for handling multiple threads. Specifically when loading/parsing a bunch of data in the background without the UI locking up.

-(void)loadSomeReallyLargeFile {
	
	NSOperationQueue *queue = [NSOperationQueue new];
	
	NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self 
																			selector:@selector(loadDataWithOperation) 
																			  object:nil];
	[queue addOperation:operation];
	[operation release];
}

- (void) loadDataWithOperation {
    
	//instantiate and run your XML/JSON load and parsing classes here
	// everything that happens here is running on a secondary thread
	
	//trigger a method on the main thread when everything's done
	[self performSelectorOnMainThread:@selector(doStuffOnMainThread) withObject:nil waitUntilDone:YES];
}

-(void)doStuffOnMainThread{
    
    //reload a your table, display the loaded data or whatever
    
}

First thing to do is create an NSOperationQueue, it takes care of all of threads for us. Then create an NSInvocationOperation, this is essentially our thread, we parse it an initial method to run on the thread. Then simply add the operation to the queue. This method will now run on a sperate thread to the UI and we can instantiate our JSON or XML parser, and after that trigger a function on the main thread by calling performSelectorOnMainThread and setting waitUntilDone boolean to YES.
Concurrency done!

Leave a Reply

Your email address will not be published. Required fields are marked *