在某个任务完成后才开始另一个任务
没什么好说的,上例子
- (void) firstOperationEntry:(id)paramObject{
NSLog(@"First Operation - Parameter Object = %@", paramObject);
NSLog(@"First Operation - Main Thread = %@", [NSThread mainThread]);
NSLog(@"First Operation - Current Thread = %@", [NSThread currentThread]);
}
- (void) secondOperationEntry:(id)paramObject{
NSLog(@"Second Operation - Parameter Object = %@", paramObject);
NSLog(@"Second Operation - Main Thread = %@", [NSThread mainThread]);
NSLog(@"Second Operation - Current Thread = %@", [NSThread currentThread]);
}
-(void)test6_14
{
NSNumber *firstNumber = [NSNumber numberWithInteger:111];
NSNumber *secondNumber = [NSNumber numberWithInteger:222];
NSInvocationOperation *firstOperation;
NSInvocationOperation *secondOperation;
NSOperationQueue *operationQueue;
firstOperation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(firstOperationEntry:) object:firstNumber];
secondOperation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(secondOperationEntry:) object:secondNumber];
[firstOperation addDependency:secondOperation];
// [firstOperation removeDependency:secondOperation];
operationQueue = [[NSOperationQueue alloc] init];
/* Add the operations to the queue */
[operationQueue addOperation:firstOperation];
[operationQueue addOperation:secondOperation];
NSLog(@"Main thread is here");
}
输出:
2014-03-12 10:27:22.158 cookbook[505:a0b] Main thread is here
2014-03-12 10:27:22.158 cookbook[505:1403] Second Operation - Parameter Object = 222
2014-03-12 10:27:22.159 cookbook[505:1403] Second Operation - Main Thread = <NSThread: 0x8950130>{name = (null), num = 1}
2014-03-12 10:27:22.159 cookbook[505:1403] Second Operation - Current Thread = <NSThread: 0x8c917d0>{name = (null), num = 2}
2014-03-12 10:27:22.160 cookbook[505:1403] First Operation - Parameter Object = 111
2014-03-12 10:27:22.160 cookbook[505:1403] First Operation - Main Thread = <NSThread: 0x8950130>{name = (null), num = 1}
2014-03-12 10:27:22.161 cookbook[505:1403] First Operation - Current Thread = <NSThread: 0x8c917d0>{name = (null), num = 2}
显然firstOperation是在secondOperation执行完成后才开始执行的。这是通过[firstOperation addDependency:secondOperation];这句实现的。
如果想取消这种依赖关系,则用 [firstOperation removeDependency:secondOperation];