SundayMonday SundayMonday - 1 month ago 13
iOS Question

NSOperation vs Grand Central Dispatch

I'm learning about concurrent programming for iOS. So far I've read about

/
NSOperationQueue
and
GCD
. What are the reasons for using
NSOperationQueue
over
GCD
and vice versa?


Sounds like both
GCD
and
NSOperationQueue
abstract away the explicit creation of
NSThreads
from the user. However the relationship between the two approaches isn't clear to me so any feedback to appreciated!

Answer

GCD is a low-level C-based API that enables very simple use of a task-based concurrency model. NSOperation and NSOperationQueue are Objective-C classes that do a similar thing. NSOperation was introduced first, but as of 10.6 and iOS 4, NSOperationQueue and friends are internally implemented using GCD.

In general, you should use the highest level of abstraction that suits your needs. This means that you should usually use NSOperationQueue instead of GCD, unless you need to do something that NSOperationQueue doesn't support.

Note that NSOperationQueue isn't a "dumbed-down" version of GCD; in fact, there are many things that you can do very simply with NSOperationQueue that take a lot of work with pure GCD. (Examples: bandwidth-constrained queues that only run N operations at a time; establishing dependencies between operations. Both very simple with NSOperation, very difficult with GCD.) Apple's done the hard work of leveraging GCD to create a very nice object-friendly API with NSOperation. Take advantage of their work unless you have a reason not to.

Caveat: On the other hand, if you really just need to send off a block, and don't need any of the additional functionality that NSOperationQueue provides, there's nothing wrong with using GCD. Just be sure it's the right tool for the job.