dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 网络请求1
[[RequestNetworkData defaultRequest] requestUrl:nil andInfo:nil andResultData:^(id obj, NSError *err) {
}];
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 网络请求2
[[RequestNetworkData defaultRequest] requestUrl:nil andInfo:nil andResultData:^(id obj, NSError *err) {
}];
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//合并
});
// 然而问题来了,网络请求这玩意儿是封装好的,并且是个异步函数,大家应该都知道,异步函数不会阻塞线程,不用等里面的内容执行完就返回了,这就导致数据还没拿到,就开始执行notify里面的代码了。后来笔者发现,原来GCD组函数还有一种用法,完美解决问题
dispatch_group_t group1 = dispatch_group_create();
dispatch_group_enter(group1);
// 网络请求
[[RequestNetworkData defaultRequest] requestUrl:nil andInfo:nil andResultData:^(id obj, NSError *err) {
dispatch_group_leave(group1);
}];
dispatch_group_enter(group1);
// 网络请求
[[RequestNetworkData defaultRequest] requestUrl:nil andInfo:nil andResultData:^(id obj, NSError *err) {
dispatch_group_leave(group1);
}];
dispatch_group_notify(group1, dispatch_get_main_queue(), ^{
//请求完成之后的处理
});
网友评论