NSOperation是一套基于GCD的在Cocoa框架中的實(shí)現(xiàn)形式,采用面向?qū)ο?/strong>的形式封裝了要異步執(zhí)行的Operation,F(xiàn)oundation framework定義了以下3種Operation:
. NSInvocationOperation,封裝了selector的operation
. NSBlockOperation,封裝了block的operation
. NSOperation,一個(gè)抽象類,需要自定義實(shí)現(xiàn)相關(guān)selector
具有以下典型特點(diǎn):
1.繼承自NSObject,支持KVO
2.支持Operation之間依賴關(guān)系(依賴關(guān)系不能是閉環(huán)的)的建立,簡(jiǎn)言之就是Operation之間執(zhí)行先后順序是可自定義的,參考dispatch_group的對(duì)多個(gè)異步task建立組任務(wù),猜想Operation的這個(gè)特征應(yīng)該是基于dispatch_group實(shí)現(xiàn)
3.支持Operation的暫停,恢復(fù)和取消
4.支持Operation執(zhí)行所在Queue優(yōu)先級(jí)和Thread優(yōu)先級(jí)的設(shè)置,
兩個(gè)方法setQueuePriority: setThreadPriority:
5.支持completion block,在Operation執(zhí)行完后會(huì)調(diào)用該completion block
以下是英文原文:
Support for the establishment of graph-based dependencies between operation objects. These dependencies prevent a given operation from running until all of the operations on which it depends have finished running. For information about how to configure dependencies, see Configuring Interoperation Dependencies.
Support for an optional completion block, which is executed after the operation’s main task finishes. (OS X v10.6 and later only.) For information about how to set a completion block, see Setting Up a Completion Block.
Support for monitoring changes to the execution state of your operations using KVO notifications. For information about how to observe KVO notifications, see Key-Value Observing Programming Guide.
Support for prioritizing operations and thereby affecting their relative execution order. For more information, see Changing an Operation’s Execution Priority.
Support for canceling semantics that allow you to halt an operation while it is executing. For information about how to cancel operations, see Canceling Operations. For information about how to support cancellation in your own operations, see Responding to Cancellation Events.
Operations are designed to help you improve the level of concurrency in your application. Operations are also a good way to organize and encapsulate your application’s behavior into simple discrete chunks. Instead of running some bit of code on your application’s main thread, you can submit one or more operation objects to a queue and let the corresponding work be performed asynchronously on one or more separate threads.
參考:Apple官方文檔