I’m learning about concurrent programming for iOS. So far I’ve read about NSOperation/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!
GCDis a low-level C-based API that enables very simple use of a task-based concurrency model.NSOperationandNSOperationQueueare Objective-C classes that do a similar thing.NSOperationwas introduced first, but as of 10.5 and iOS 2,NSOperationQueueand friends are internally implemented usingGCD.In general, you should use the highest level of abstraction that suits your needs. This means that you should usually use
NSOperationQueueinstead ofGCD, unless you need to do something thatNSOperationQueuedoesn’t support.Note that
NSOperationQueueisn’t a “dumbed-down” version of GCD; in fact, there are many things that you can do very simply withNSOperationQueuethat take a lot of work with pureGCD. (Examples: bandwidth-constrained queues that only run N operations at a time; establishing dependencies between operations. Both very simple withNSOperation, very difficult withGCD.) Apple’s done the hard work of leveraging GCD to create a very nice object-friendly API withNSOperation. 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
NSOperationQueueprovides, there’s nothing wrong with using GCD. Just be sure it’s the right tool for the job.