iOS 多線程(NSOperationQueue)

來源:互聯網
上載者:User

標籤:

1.就基本使用

NSInvocationOperation

//1.建立操作對象,封裝需要執行的任務    NSInvocationOperation * operation =[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download) object:nil];        //2.執行操作(預設情況下,如果操作沒有放到隊列queue中,都是同步執行)    [operation start];- (void)download{    NSLog(@"--------下載圖片-----%@",[NSThread currentThread]);}

 

NSBlockOperation

 //1.封裝操作    NSBlockOperation * operation=[NSBlockOperation blockOperationWithBlock:^{        NSLog(@"--------下載圖片-----%@",[NSThread currentThread]);    }];        [operation addExecutionBlock:^{         NSLog(@"--------下載圖片1-----%@",[NSThread currentThread]);    }];    [operation addExecutionBlock:^{         NSLog(@"--------下載圖片2-----%@",[NSThread currentThread]);    }];        //2.執行操作    [operation start];        //注意:只要NSBlockOperation封裝的運算元>1,就會非同步執行操作

 

 NSOperationQueue 操作隊列

 //建立操作隊列    NSOperationQueue * queue =[[NSOperationQueue alloc]init];    NSInvocationOperation *operation1 =[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download) object:nil];    NSInvocationOperation * operation2 =[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(run) object:nil];        NSBlockOperation * operation3 =[NSBlockOperation blockOperationWithBlock:^{        NSLog(@"--------下載圖片2-----%@",[NSThread currentThread]);            }];        [operation3 addExecutionBlock:^{        NSLog(@"--------run2-----%@",[NSThread currentThread]);    }];            [queue addOperation:operation1];    [queue addOperation:operation2];    [queue addOperation:operation3]; //將操作放在隊列裡才能非同步作業

 

*設定最大並發數

- (void)setMaxConcurrentOperationCount:(NSInteger )cnt;

 

*設定依賴

[opetationB  addDependency:operationA];//操作B依賴於操作A       A執行完才會執行B

 

iOS 多線程(NSOperationQueue)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.