1. 程式人生 > >NSOperation添加操作依賴和監聽

NSOperation添加操作依賴和監聽

ren min ack fff 封裝 add number dep ted

//創建隊列

NSOperationQueue *queue = [[NSOperationQueue alloc]init];

//封裝操作

NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{

NSLog(@"1-----------%@",[NSThread currentThread]);

}];

NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{

NSLog(@"2-----------%@",[NSThread currentThread]);

}];

NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{

NSLog(@"3-----------%@",[NSThread currentThread]);

}];

NSBlockOperation *op4 = [NSBlockOperation blockOperationWithBlock:^{

NSLog(@"4-----------%@",[NSThread currentThread]);

}];

   op3.completionBlock = ^{//添加監聽,操作執行完畢後 回調

NSLog(@"op3執行完畢。。");

};

//添加操作依賴 4->3->2->1 // 添加操作依賴能控制多任務並發的執行順序,不能設置循環依賴,可以跨隊列添加依賴

[op3 addDependency:op4];

[op2 addDependency:op3];

[op1 addDependency:op2];

//添加到隊列中

[queue addOperation:op1];

[queue addOperation:op2];

[queue addOperation:op3];

[queue addOperation:op4];

執行結果:

2019-02-22 23:59:43.749883+0800 下載圖片[15917:488100] 4-----------<NSThread: 0x600000e28100>{number = 3, name = (null)}

2019-02-22 23:59:43.750367+0800 下載圖片[15917:488101] 3-----------<NSThread: 0x600000e34000>{number = 4, name = (null)}

2019-02-22 23:59:43.750513+0800 下載圖片[15917:488100] 2-----------<NSThread: 0x600000e28100>{number = 3, name = (null)}

2019-02-22 23:59:43.750654+0800 下載圖片[15917:488100] 1-----------<NSThread: 0x600000e28100>{number = 3, name = (null)}

NSOperation添加操作依賴和監聽