NSOperation:
1. NSInvocationOperation
ex:
NSInvocationOperation *invacationOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomethingWithObj:) object:obj];
get result:
id result = [invacationOperation result];
2. NSBlockOperation
ex:
NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:
^{
//do something
}];
3. 自定義(繼承)NSOperation
- NSInvocationOperation & NSBlockOperation 兩者實際上無太大差別
- Start & Cancel 一個 Operation
[operation start];
[operation cancel];
- 設置Operation的completionBlock:
completionBlock實現原理是對Operation的isFinnshed字段進行KVO(Key-Value Observing),當監聽到isFinnished變成YES时,就执行completionBlock。
operation.completionBlock =
^{
NSLog(@"finished");
};
NSOperationQueue:
NSOperationQueue是一个Operation执行队列,你可以将任何你想要执行的Operation添加到Operation Queue中,以在队列中执行。'
- Operation的依賴關係:
[operation addDependency:anotherOperation];
[operation removeDependency:anotherOperation];
如果将这些Operation和它所依赖的Operation加如队列中,那么Operation只有在它依赖的Operation都执行完毕后才可以被执行。
- Operation在队列中执行的优先级:
Operation在队列中默认是按FIFO(First In First Out)顺序执行的。同时我们可以为单个的Operation设置一个执行的优先级,打乱这个顺序。
- 最大並行Operation數目:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 1;
* 實驗結果:區域變數中的NSBlockOperation 須先經過init, 才能在其他function中被cancel.
ex:
NSBlockOperation *op2 = [[NSBlockOperation alloc] init];
__weak NSBlockOperation *weakOperation = op2;
[op2 addExecutionBlock:
^{
//while (true)
for(int i = 0; i<30; i++)
{
NSLog(@"op2 %@", op2);
if ([op2 isCancelled])
{
return;
}
[NSThread sleepForTimeInterval:1];
}
}];