需求:两个异步任务都完成后, 回到主线程
/**
1.下载图片1和图片2
2.将图片1和图片2合并成一张图片后显示到imageView上
思考:
* 下载图片 : 子线程
* 等2张图片都下载完毕后, 才回到主线程
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 创建一个组
dispatch_group_t group = dispatch_group_create();
// 开启一个任务下载图片1
__block UIImage *image1 = nil;
dispatch_group_async(group, global_queue, ^{
image1 = [self imageWithURL:@"http://news.baidu.com/z/resource/r/image/2014-06-22/2a1009253cf9fc7c97893a4f0fe3a7b1.jpg"];
});
// 开启一个任务下载图片2
__block UIImage *image2 = nil;
dispatch_group_async(group, global_queue, ^{
image2 = [self imageWithURL:@"http://news.baidu.com/z/resource/r/image/2014-06-22/b2a9cfc88b7a56cfa59b8d09208fa1fb.jpg"];
});
// 同时执行下载图片1\下载图片2操作
// 等group中的所有任务都执行完毕, 再回到主线程执行其他操作
dispatch_group_notify(group, main_queue, ^{
self.imageView1.image = image1;
self.imageView2.image = image2;
// 合并
UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 100), NO, 0.0);
[image1 drawInRect:CGRectMake(0, 0, 100, 100)];
[image2 drawInRect:CGRectMake(100, 0, 100, 100)];
self.bigImageView.image = UIGraphicsGetImageFromCurrentImageContext();
// 关闭上下文
UIGraphicsEndImageContext();
});
// if (self.log == NO) {
// NSLog(@"-------touchesBegan");
// self.log = YES;
// }
// static dispatch_once_t onceToken;
// dispatch_once(&onceToken, ^{
// NSLog(@"-------touchesBegan");
// });
}