iOS開發系列-NSOperation

來源:互聯網
上載者:User

標籤:好的   image   cut   對象   定義   current   nil   ati   具體步驟   

概述

NSOperation是基於GCD的封裝更加物件導向,在使用上也是有任務跟隊列的概念,分別對應兩個類NSOperation 、NSOperationQueue

NSOperation和NSOperationQueue實現多線程的具體步驟

  • 現將需要執行的操作封裝到一個NSOperation對象中。
  • 然後將NSOperation對象添加到NSOperationQueue中
  • 系統會自動將NSOperationQueue中的NSOperation取出來
  • 將取出的NSOperation封裝的操作放到一條線程中執行
NSOperation

NSOperation是一個抽象類別,使用時候需要使用其子類。NSOperation總共有兩個子類。

  • NSInvocationOperation
  • NSBlockOperation

開發中一般NSOperation子類通常與NSOperationQueue一起使用才能更好的開闢線程。

NSOperationQueue

NSOperation可以調用start方法類執行任務,但預設是同步的。如果將NSOperation添加到NSOperationQueue中執行,系統會自動非同步執行NSOperation中的操作。

NSOperationQueue只用兩種類型,分別是主隊列跟非主隊列(包含串列、並發)。兩種隊列的擷取方式:

[NSOperationQueue mainQueue]; // 主隊類[[NSOperationQueue alloc] init]; // 非主隊列

凡是添加到主隊列的任務都是在主線程中執行。非主隊列的任務會自動添加到子線程中執行。並發跟串列通過隊列的maxConcurrentOperationCount決定。

#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];        NSOperationQueue *queue = [[NSOperationQueue alloc] init];        NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task) object:nil];    [queue addOperation:operation];//    [operation start];        NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{        NSLog(@"------------%@", [NSThread currentThread]);    }];    // 添加額外的任務才會在子線程執行    [blockOperation addExecutionBlock:^{        NSLog(@"------------%@", [NSThread currentThread]);    }];    [queue addOperation:blockOperation];    //    [blockOperation start];    }- (void)task{    NSLog(@"------------%@", [NSThread currentThread]);}

一旦NSOperation添加進NSOperationQueue,無須調用NSOperation的start方法,內部自動回調用NSOperation的start。

開發中還可以自訂NSOperation的方式,重寫main方法將任務封裝進來。如果任務的代碼比較多,在很多程式的很多地方都需要使用,建議採用這種方式。

#import "FMOperation.h"@implementation FMOperation- (void)main{    // 封裝任務    }@end

iOS開發系列-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.