GCD异步下载
#pragma mark 下载
- (void)download:(id)sender {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 异步执行下载任务
dispatch_async(queue, ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://localhost:8080/Server/images/image01.jpg"]];
UIImage *image = [UIImage imageWithData:data];
// 获取跟主线程相关的队列
dispatch_queue_t main = dispatch_get_main_queue();
dispatch_async(main, ^{
self.imageView.image = image;
});
});
dispatch_async(queue, ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://localhost:8080/Server/images/image02.jpg"]];
UIImage *image = [UIImage imageWithData:data];
// 获取跟主线程相关的队列
dispatch_queue_t main = dispatch_get_main_queue();
dispatch_async(main, ^{
self.imageView2.image = image;
});
});
}
#pragma mark 同步执行
- (void)sync {
// 获取一个全局队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_sync(queue, ^{
NSLog(@"执行了一个异步任务-%@", [NSThread currentThread]);
});
}
#pragma mark 迭代
- (void)diedai {
// 手动创建队列
// dispatch_queue_t queue = dispatch_queue_create("cn.com.queue", NULL);
// 手动管理内存
// dispatch_release(queue)
// 获取一个全局队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(10, queue,
^(size_t i) {
NSLog(@"%i", i);
});
}
// 等group里面的所有任务都执行完后,再回到主线程调用block
- (void)count {
int a = 2;
int b = 3;
__block int c;
__block int d;
// 创建一个组
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 并发、异步执行任务
dispatch_group_async(group, queue, ^{
c = a + b; // 5秒;
});
dispatch_group_async(group, queue, ^{
d = a * b; // 3秒
});
dispatch_queue_t main = dispatch_get_main_queue();
// 等group里面的所有任务都执行完后,再回到主线程调用block
dispatch_group_notify(group, main, ^{
int e = c + d;
NSLog(@"e=%i %@", e, [NSThread currentThread]);
dispatch_release(group);
});
}