Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which tasks are more suitable to NSOperation than GCD? [duplicate]

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.

like image 398
dubbeat Avatar asked Dec 03 '10 11:12

dubbeat


People also ask

What is an advantage of using NSOperation vs GCD?

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.

What is the difference between GCD and NSOperation?

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 .

What is NSOperation queue in Swift?

A queue that regulates the execution of operations.

What is GCD in iOS Swift?

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.


2 Answers

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.

like image 163
Yuji Avatar answered Sep 21 '22 04:09

Yuji


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.

like image 41
scaba Avatar answered Sep 24 '22 04:09

scaba