views:

7223

answers:

3

I've been looking for some concrete scenarios for when NSOperation on the iPhone is an ideal tool to use in an application. To my understanding, this is a wrapper around writing your own threaded code. I haven't seen any Apple demo apps using it, and I'm wondering if I'm missing out on a great tool instead of using NSThread.

The ideal solution here would be to describe a use-case scenario for NSOperation and how you would use it to solve your problem(s).

+15  A: 

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.

e.James
There's another tutorial here: http://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/
wbyoung
I would also suggest going over the Standord Class materials. They make extensive use of NSOperation to async load images in the flickr example. They are available on iTunes for free.
Jab
+2  A: 

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'.

Jason M.
Actually it isn't *really* threadsafe, there is a problem with it on Mac OS X 10.5. See http://www.mikeash.com/?page=pyblog/dont-use-nsoperationqueue.html. Though they mention that the iPhone seems to be immune to it because of the single core processor
nduplessis
+8  A: 

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 *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(updateXML) object:nil];
[[(MyAppDelegate *)[[UIApplication sharedApplication] delegate] sharedOperationQueue] addOperation:updateOperation];
[op release];
nduplessis