Which tasks would be better suited to using NSOperation
as opposed to using GCD
when programming for the iPhone?
To me they seem to do the same thing. I can't see the strengths and weaknesses one has over the other.
Benefits of NSOperationYou can Pause, Cancel, Resume an NSOperation . With Grand Central Dispatch, you no longer have control or insight into the execution of that task. The NSOperation API is more flexible in that respect, giving the developer control over the operation's life cycle.
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.5 and iOS 2, NSOperationQueue and friends are internally implemented using GCD .
A queue that regulates the execution of operations.
Grand Central Dispatch (GCD) is a low-level API for managing concurrent operations. It can help improve your app's responsiveness by deferring computationally expensive tasks to the background. It's an easier concurrency model to work with than locks and threads.
NSOperation
is built on top of GCD, so the question is more about whether you use NSOperation
or pass a block directly to GCD.
An NSOperation
is bulky and needs more boiler-plate codes to set it up, but it has a lot more functionality. You can create the same NSOperation
subclass in various parts of your code and put them into the queue and run it.
Passing a block to GCD by e.g. dispatch_async
is quick and disposable. You typically don't reuse a block anywhere else; you just set up a block which is executed only at that point of the code, passes it to the GCD or other APIs, and quickly go on.
So each has its merits.
Apparently, NSOperationQueue is built on GCD as of iOS 4; the docs just haven't been updated. Check this posting by an Apple employee here: https://devforums.apple.com/message/352770 (You may need to create an account) So, you should follow Mike Abdullah's advice and use the simplest API for the task at hand. dispatch_async is lower level, usually C-type stuff (but not limited to), and is good for one-shot and sequential type deals (fire this block on this queue, FTW). NSOperationQueues are higher level, Objective-C stuff, and are good if you are adding a lot of operations at various points in your code, and/or need to manage concurrency, priorities and dependencies. At least that's how I use them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With