GCD VS. NSOperationQueue

2017-08-07  本文已影响88人  三秋树下

1.GCD的优点:GCD的实现是底层的,而且更加的轻量级。而NSOperation是更加复杂和重量级的语法。

  1. NSOperation的优点:
    1、可控性
    具体体现在:可对NSOperation进行暂停、取消、恢复操作。
    2、依赖性
    体现在:如果对两个Operation设置依赖关系,只有当依赖为true的时候,operation才会进行。
    3、状态检测
    体现在:可监控到一个operation或operation queue的状态是ready,executing还是finished.
    4.操作队列最大数目限制
    可以设置最大operations数目限制。

最后GCD VS. NSOperation如何选择?
黄金法则:当你需要对操作的队列进行更多控制那就选择NSOperation吧,当你只是需要一些简单的操作时(如你只是想切到后台线程进行一些不复杂的操作时)大胆使用GCD也是不错的选择


来自Stack Overflow的回答

NSOperation and NSOperationQueue are Objective-C classes.
NSOperationQueue is objective C wrapper over GCD. If you are using NSOperation, then you are implicitly using Grand Central Dispatch.

GCD advantage over NSOperation:
i. implementation
For GCD implementation is very light-weight
NSOperationQueue is complex and heavy-weight

NSOperation advantages over GCD:

i. Control On Operation
you can Pause, Cancel, Resume an NSOperation

ii. Dependencies
you can set up a dependency between two NSOperations
operation will not started until all of its dependencies return true for finished.

iii. State of Operation
can monitor the state of an operation or operation queue. ready ,executing or finished

iv. Max Number of Operation
you can specify the maximum number of queued operations that can run simultaneously

When to Go for GCD or NSOperation
when you want more control over queue (all above mentioned) use NSOperation and for simple cases where you want less overhead (you just want to do some work "into the background" with very little additional work) use GCD

NSOperation 和 NSOperationQueue 是基于OC的API 类。
NSOperationQueue是GCD的OC语法封装,如果你使用了NSOperation,其实间接的使用了GCD.

上一篇下一篇

猜你喜欢

热点阅读