문제

This question already has an answer here:

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.

도움이 되었습니까?

해결책

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.

As always with such questions, use the simplest API available. Measure if it's a performance problem and then reevaluate if needed.

One thing that I don't believe has been mentioned here is that NSOperations can be cancelled during execution, whereas a block is guaranteed to complete once execution has begun. Having said that, a GCD queue can be suspended (dispatch_suspend()), so that any blocks following the currently executing blocks will not be executed.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top