Dispatch Group的使用
来源:程序员人生 发布时间:2015-04-14 08:50:38 阅读次数:2344次
转自MJ偶像
Dispatch Group的使用
假定有这样1个需求:从网络上下载两张不同的图片,然后显示到不同的UIImageView上去,1般可以这样实现
-
-
- (UIImage *)imageWithURLString:(NSString *)urlString {
-
NSURL *url = [NSURL URLWithString:urlString];
-
NSData *data = [NSData dataWithContentsOfURL:url];
-
return [UIImage imageWithData:data];
-
}
-
-
- (void)downloadImages {
-
-
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
-
-
NSString *url1 = @"http://car0.autoimg.cn/upload/spec/9579/u_20120110174805627264.jpg";
-
UIImage *image1 = [self imageWithURLString:url1];
-
-
-
NSString *url2 = @"http://hiphotos.baidu.com/lvpics/pic/item/3a86813d1fa41768bba16746.jpg";
-
UIImage *image2 = [self imageWithURLString:url2];
-
-
-
dispatch_async(dispatch_get_main_queue(), ^{
-
self.imageView1.image = image1;
-
-
self.imageView2.image = image2;
-
});
-
});
-
}
虽然这类方案可以解决问题,但其实两张图片的下载进程其实不需要按顺序履行,并发履行它们可以提高履行速度。有个注意点就是必须等两张图片都下载终了后才能回到主线程显示图片。Dispatch Group能够在这类情况下帮我们提升性能。下面先看看Dispatch
Group的用途:
我们可使用dispatch_group_async函数将多个任务关联到1个Dispatch Group和相应的queue中,group会并发地同时履行这些任务。而且Dispatch Group可以用来阻塞1个线程, 直到group关联的所有的任务完成履行。有时候你必须等待任务完成的结果,然后才能继续后面的处理。
下面用Dispatch Group优化上面的代码:
-
-
- (UIImage *)imageWithURLString:(NSString *)urlString {
-
NSURL *url = [NSURL URLWithString:urlString];
-
NSData *data = [NSData dataWithContentsOfURL:url];
-
-
return [[UIImage alloc] initWithData:data];
-
}
-
-
- (void)downloadImages {
-
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
-
-
-
dispatch_async(queue, ^{
-
-
dispatch_group_t group = dispatch_group_create();
-
-
__block UIImage *image1 = nil;
-
__block UIImage *image2 = nil;
-
-
-
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
-
-
NSString *url1 = @"http://car0.autoimg.cn/upload/spec/9579/u_20120110174805627264.jpg";
-
image1 = [self imageWithURLString:url1];
-
});
-
-
-
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
-
-
NSString *url2 = @"http://hiphotos.baidu.com/lvpics/pic/item/3a86813d1fa41768bba16746.jpg";
-
image2 = [self imageWithURLString:url2];
-
});
-
-
-
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
-
self.imageView1.image = image1;
-
self.imageView2.image = image2;
-
-
-
-
-
[image1 release];
-
[image2 release];
-
});
-
-
-
dispatch_release(group);
-
});
-
}
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠