NSOperation:
1、NSOperation其实是一个任务的封装,靠NSOperationQueue实现多线程;
2、NSOperation底层实现:在OS X v10.6(iOS 4)之前通过NSThread实现,OS X v10.6(iOS 4)之后通过GCD实现;(Operation queues usually provide the threads used to run their operations. In OS X v10.6 and later, operation queues
use the libdispatch
library (also known as Grand Central Dispatch) to initiate the execution of their operations. As a result, operations are always executed on a separate thread, regardless of whether they are designated as concurrent or non-concurrent
operations. In OS X v10.5, however, operations are executed on separate threads only if their isConcurrent
method
returns NO
. If that method returns YES
, the operation object is expected to create its own thread (or start some asynchronous operation); the queue does not provide a thread for it.)
3、NSOperationQueue分为concurrent(由Operation自己实现多线程)和non-concurrent方式,OS X v10.6(iOS 4)之前NSOperationQueue根据isConcurrent判断是否给该Operation分配一个线程(YES不单独分配,NO单独分配一个线程),OS X v10.6(iOS 4)之后NSOperationQueue统一按照non-councurrent方式处理(如果使用Queue方式,苹果官NSOperation官方文档;
4、NSOperation可以监测线程运行的各种状态,并且可以cancel掉一个NSOperation包括正在运行的Operation(需要自己监测isCanceled实现线程退出),而GCD一旦创建就没办法控制和监控;
5、NSOperation被cancel之后,如果已经在运行态会尽可能快的终止任务移除队列,如果还没有在运行态OS X v10.6之后会尽可能快的调用该Operation然后终止任务移除队列,OS X v10.6之前则不会提高其优先级按照原来的顺序调用Operation.start然后终止任务移除队列;
6、手动触发一个isReady=NO的NSOperation会触发一个异常;
GCD:
1、针对多核进行了优化;
2、是使用最方便的一直多线程实现方式;
3、一般利用block实现,在代码连续性上更为简洁明了;