NSOperation 依賴關系,就像你和女友,互相需要對方一樣。非常有意思。
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//操作依賴
//處理圖片的耗時操作在子線程中執行
NSBlockOperation *blockOp = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"blockOp 下載圖片 thread = %@",[NSThread currentThread]);
}];
NSBlockOperation *blockOp1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"blockOp1 給圖片添加水印 thread = %@",[NSThread currentThread]);
}];
NSBlockOperation *blockOp2 = [NSBlockOperation blockOperationWithBlock:^{
[NSThread sleepForTimeInterval:2.0];
NSLog(@"blockOp2 保存圖片 thread = %@",[NSThread currentThread]);
}];
//給blockOp1添加依賴關系,使blockOp1在blcokOp執行結束後執行
[blockOp1 addDependency:blockOp];//也就是下載結束之後再給圖片添加水印,然後保存圖片。一種依賴關系
[blockOp2 addDependency:blockOp1];
//創建隊列(把上面要干的事情丟到隊列中同時執行--有點類似GCD中的異步,並發,開啟了多個線程)
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
//添加到隊列
[queue addOperation:blockOp];
[queue addOperation:blockOp1];
[queue addOperation:blockOp2];
//設置隊列中操作同時執行的最大數目,也就是說當前隊列中呢最多由幾個線程在同時執行,一般情況下允許最大的並發數2或者3
[queue setMaxConcurrentOperationCount:3];
//
for (int i = 0; i<50; i++) {
NSBlockOperation *blockOpp = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"blockOpp i = %d thread = %@",i,[NSThread currentThread]);
}];
[queue addOperation:blockOpp];
}
//刷新UI的操作依賴關系必須在主線程中執行
NSBlockOperation *blocOpMain = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"blockOpMain 刷新UI 顯示圖片,thread = %@",[NSThread currentThread]);
}];
//這兩個操作的依賴關系,跨隊列
[blocOpMain addDependency:blockOp2];
//主隊列
[[NSOperationQueue mainQueue]addOperation:blocOpMain];
}
@end