iOS多線程編程之NSOperation,nsoperation

來源:互聯網
上載者:User

iOS多線程編程之NSOperation,nsoperation

NSOperation有兩種方法:

1>.NSInvocationOperation:建立一個operation,並用selecter指向執行的程式碼片段

2>.NSBlockOperation:建立一個operation,並將執行的代碼放在block塊中.

1.NSInvocationOperation多線程方法:

建立方法:

- (void)invocationOperation {NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run1) object:nil];NSOperationQueue *queue = [[NSOperationQueue alloc] init];[queue addOperation:operation1];}

- (void)run1{NSLog(@"runing1---%@",[NSThread currentThread]);}

2.NSBlockOperation多線程方法:

建立方法:

- (void)blockOperation1 {NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{NSLog(@"blockOperation---%@",[NSThread currentThread]);}];operation.completionBlock = ^{NSLog(@"finish!-----");};NSOperationQueue *queue = [[NSOperationQueue alloc] init];[queue addOperation:operation];}


3.從子線程回到主線程重新整理UI方法:

performSelectorOnMainThread: withObject: waitUntilDone:

4.多個operation在queue中的執行順序是可以設定的.

在添加到queue之前設定operation之間的依賴關係:

[operation2 addDependency:operation1];
operation2依賴於operation1=>2在1的後邊執行.此時如果queue中只有2個operation的話不會多建立一個子線程的,進程中只有主線程和operation1的那個子線程.畢竟順序執行多開一個子線程是浪費的嘛.

5.queue中可以設定同時最多的線程數量

queue.maxConcurrentOperationCount = 3;

--end




著作權聲明:本文為博主原創文章,轉載請註明來源:http://blog.csdn.net/zhangwenhai001

聯繫我們

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