給任務(wù)添加依賴 addDependency:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
sleep(5);
NSLog(@"任務(wù) 1%@",[NSThread currentThread]);
}];
NSOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
sleep(6);
NSLog(@"任務(wù) 2%@",[NSThread currentThread]);
}];
NSOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"任務(wù) 3%@",[NSThread currentThread]);
}];
//讓任務(wù)3在任務(wù)1完成后再執(zhí)行
[op3 addDependency:op1];
//讓任務(wù)1在任務(wù)2完成后再執(zhí)行
[op1 addDependency:op2];
[queue addOperations:@[op1, op2, op3] waitUntilFinished:YES];
運(yùn)行結(jié)果為:
2018-03-02 17:11:40.932543+0800 平常測試[8147:1428152] 任務(wù) 2<NSThread: 0x600000264f80>{number = 3, name = (null)}
2018-03-02 17:11:45.937063+0800 平常測試[8147:1428159] 任務(wù) 1<NSThread: 0x60000026ea40>{number = 4, name = (null)}
2018-03-02 17:11:45.937501+0800 平常測試[8147:1428152] 任務(wù) 3<NSThread: 0x600000264f80>{number = 3, name = (null)}