线程间实现通信,NSOperation的代码:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self downLoadImageAndShow];
}
- (void)downLoadImageAndShow{
// 获取图片属性
__block UIImage * image1 = [[UIImage alloc] init];
__block UIImage * image2 = [[UIImage alloc] init];
//1. 创建 非主队列
NSOperationQueue * queue = [[NSOperationQueue alloc] init];
//2. 创建 任务 下载图片1;
NSBlockOperation * op1 = [NSBlockOperation blockOperationWithBlock:^{
NSString * urlStr = [NSString stringWithFormat:@"https://zuoye2.xinkaoyun.com/awm/35/iOS_09060620200720110101.jpeg"];
NSURL * url = [NSURL URLWithString:urlStr];
NSData * data = [NSData dataWithContentsOfURL:url];
image1 = [UIImage imageWithData:data];
}];
//3. 创建 任务 下载图片2;
NSBlockOperation * op2 = [NSBlockOperation blockOperationWithBlock:^{
NSString * urlStr = [NSString stringWithFormat:@"https://zuoye2.xinkaoyun.com/awm/35/iOS_08160320200720104454.jpeg"];
NSURL * url = [NSURL URLWithString:urlStr];
NSData * data = [NSData dataWithContentsOfURL:url];
image2 = [UIImage imageWithData:data];
}];
//4.合成图片
NSBlockOperation * op3 = [NSBlockOperation blockOperationWithBlock:^{
//开启图形上下文 并设置上下文宽高
UIGraphicsBeginImageContext(CGSizeMake(200, 200));
//图片画图
[image1 drawInRect:CGRectMake(0, 0, 100, 100)];
image1 = nil;
[image2 drawInRect:CGRectMake(0, 100, 100, 100)];
image2 = nil;
//根据图片上下文获取图片
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
//关闭上下文
UIGraphicsEndImageContext();
//回到主线程 刷新UI
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.iconImageView.image = image;
}];
}];
//添加依赖,由于异步执行,先后顺序不可控
[op3 addDependency:op2];
[op2 addDependency:op1];
//将任务添加到队列
[queue addOperation:op1];
[queue addOperation:op2];
[queue addOperation:op3];
}
运行结果:

网友评论