iosNSOperation依赖关系

前端之家收集整理的这篇文章主要介绍了iosNSOperation依赖关系前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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添加依赖关系,使blockOp1blcokOp执行结束后执行

[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

原文链接:https://www.f2er.com/javaschema/284842.html

猜你在找的设计模式相关文章