iOS GCD
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- //耗时的操作
- NSURL * url = [NSURL URLWithString:@"http://avatar.csdn.net/2/C/D/1_totogo2010.jpg"];
- NSData * data = [[NSData alloc]initWithContentsOfURL:url];
- UIImage *image = [[UIImage alloc]initWithData:data];
- if (data != nil) {
- dispatch_async(dispatch_get_main_queue(), ^{
- //刷新数据
- self.imageView.image = image;
- });
- }
- });
-
系统给每一个应用程序提供了三个concurrent dispatch queues。这三个并发调度队列是全局的,它们只有优先级的不同。因为是全局的,我们不需要去创建。我们只需要通过使用函数dispath_get_global_queue去得到队列,如下:
1.dispatch_queue_t globalQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
这里也用到了系统默认就有一个串行队列main_queue
2.dispatch_queue_t mainQ = dispatch_get_main_queue();
虽然dispatch queue是引用计数的对象,但是以上两个都是全局的队列,不用retain或release。
2.使用Dispatch Group异步下载两张图片
@interface ViewController ()
@property (nonatomic, strong) UIImage *imageOne;
@property (nonatomic, strong) UIImage *imageTwo;
@property (nonatomic, weak) UILabel *textLabel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self operation1];
}
- (void)operation1
{
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 450, 0, 0)];
textLabel.text = @"正在下载图片";
[textLabel sizeToFit];
[self.view addSubview:textLabel];
self.textLabel = textLabel;
[self group];
NSLog(@"在下载图片的时候,主线程貌似还可以干点什么");
}
- (void)group
{
UIImageView *imageView = [[UIImageView alloc] init];
[self.view addSubview:imageView];
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create("com.wuniu.www", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_async(group, queue, ^{
NSLog(@"正在下载第一张图片");
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://img3.imgtn.bdimg.com/it/u=3484903974,2907035455&fm=206&gp=0.jpg"]];
NSLog(@"第一张图片下载完毕");
self.imageOne = [UIImage imageWithData:data];
});
dispatch_group_async(group, queue, ^{
NSLog(@"正在下载第二张图片");
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://img4.imgtn.bdimg.com/it/u=2718132976,3419769724&fm=206&gp=0.jpg"]];
NSLog(@"第二张图片下载完毕");
self.imageTwo = [UIImage imageWithData:data];
});
dispatch_group_notify(group, queue, ^{
UIGraphicsBeginImageContext(CGSizeMake(400, 200));
[self.imageOne drawInRect:CGRectMake(0, 0, 150, 200)];
[self.imageTwo drawInRect:CGRectMake(150, 0, 150, 200)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
UIImageView *imageView = [[UIImageView alloc] initWithImage:newImage];
[self.view addSubview:imageView];
self.textLabel.text = @"图片合并完毕";
});
});
}
//打印输出
2016-08-18 15:26:27.750 LX[66966:7575374] 正在下载第一张图片
2016-08-18 15:26:27.750 LX[66966:7575372] 正在下载第二张图片
2016-08-18 15:26:27.750 LX[66966:7575341] 在下载图片的时候,主线程貌似还可以干点什么
2016-08-18 15:26:28.076 LX[66966:7575372] 第二张图片下载完毕
2016-08-18 15:26:28.080 LX[66966:7575374] 第一张图片下载完毕