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