NSOperation on the iPhone NSOperation on the iPhone multithreading multithreading

NSOperation on the iPhone


Cocoa Is My Girlfriend has a good tutorial on the use of NSOperation and NSOperationQueue. The tutorial makes use of NSOperation to download several webpages simultaneously in separate threads.

Also, see this article from Mac Research.


The way I use it in my iPhone apps is to basically create an NSOperationQueue member in my application delegate and make it available through a property. Then every time I need to run something in the background, e.g. download some XML I'll just create an NSInvocationOperation and send it to the queque.

NSInvocationOperation *operationToPerform = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(updateXML) object:nil];[[(MyAppDelegate *)[[UIApplication sharedApplication] delegate] sharedOperationQueue] addOperation:operationToPerform];[op release];


In a word: NSOperationQueue

NSOperationQueue is thread safe (you can add operations to it from different threads without the need for locks) and enables you to chain NSOp objects together.

My Flickr iPhone app, Reflections, uses NSOperation and NSOperationQueue extensively to manage downloading images and XML.

Caveat: Make sure you read, re-read, and understand what the docs mean when they talk about 'concurrency'.