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實現,在代碼連續性上更爲簡潔明瞭;