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