iOS 8:【轉】NSOperation 筆記

來源:互聯網
上載者:User

標籤:

源地址:http://fann.im/blog/2014/02/23/nsoperation/

iOS 下的多線程編程有 NSOperation 和 Grand Central Dispatch(GCD) 兩種,簡單記一些 NSOperation 的使用注意。

NSOperationQueue 相當於一個操作池,operation 添加進來後會按照 First-In-First-Out(FIFO) 的策略自動執行。operation 一般會添加到應用全域共用的自訂 queue,這樣避免阻塞主線程的執行。

一些簡單的多線程需求沒必要動用 NSOperation 這個大傢伙,NSInvocationOperation 就很方便:

NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(anyWork) object:nil];[operationQueue addOperation:op];- (void)anyWork{ //perform any work in operation}

NSInvocationOperation 不是很方便共用操作,如果某個操作會在很多地方需要,就可以做個 NSOperation 子類封裝:

@implementation CustomOperation- (void)main{ //perform any work in operation}@end

這個子類只實現了 main 方法,相較 NSInvocationOperation 方便共用。如果需要對操作做更多細緻化的功能,比如狀態控制,就需要更加複雜的繼承實現,參見 AFURLConnectionOperation,這種情況下不繼承 main,而是繼承實現 start cancel等,然後通過 KVO 手動控制操作狀態的切換。

NSOperation 可以設定依賴,A 操作依賴 B 操作完成後才能做,那麼就可以設定 B 為 A 的依賴 [A addDependency:B];.

如果各個操作之間沒有依賴關係,但是又需要在全部操作都完成後做一些善後工作,有兩個解決方案,一是添加所有操作為善後操作的依賴,這樣所有其他動作完成後善後操作才會執行,這個方法較為死板,或者可以用 KVO 監聽隊列運算元,等操作都完成後隊列操作為空白的時候做善後工作:

[operationQueue addObserver:self forKeyPath:@"operationCount" options:0 context:nil];- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ if (object == operationQueue && [keyPath isEqualToString:@"operationCount"]) { if (operationQueue.operationCount == 0) { // any final operation. } } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; }}
NSOperation or GCD

NSOperation 和 GCD 都能滿足多線程需要,那麼該選哪個?When to use NSOperation vs. GCD 的觀點:

Always use the highest-level abstraction available to you, and drop down to lower-level abstractions when measurement shows that they are needed.

NSOperation 相比 GCD 提供了更多功能,比如操作執行狀態,操作執行的暫停、取消,比如操作之間的依賴,比如控制操作隊列同一時間可執行操作的數量。

GCD 相比 NSOperation 使用方便,系統開銷小效能好。

實際項目中較為簡單的小操作直接 GCD,靈活方便;規模較大控制複雜的操作還是通過 NSOperation 為好,也能享用進階 API 提供的方便。

iOS 8:【轉】NSOperation 筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.