dispatch_group_t group = dispatch_group_create();
// dispatch_group_enter(group);
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"A");
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"B");
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"C");
});
//A B C都执行完才执行D
dispatch_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"D");
});
但是有的时候可能需要执行异步请求在线程中,这种方式就不管用了。因为异步函数不会阻塞线程,不用等里面的内容执行完就返回了, 这就导致数据还没拿到,就开始执行notify里面的代买了。所以这种情况得用下面这种方法:
dispatch_group_enter(group);
[NetWork sendGetRequestURL:@"www.baidu.com" parameters:nil completionBlockWithSuccess:^(NSDictionary *resultDict) {
NSLog(@"%@", resultDict);
dispatch_group_leave(group);
} andFailure:^(NSError *error, NSString *errorMsg) {
NSLog(@"%@", error);
}];
dispatch_group_enter(group);
[NetWork sendGetRequestURL:@"www.souhu.com" parameters:nil completionBlockWithSuccess:^(NSDictionary *resultDict) {
NSLog(@"%@", resultDict);
dispatch_group_leave(group);
} andFailure:^(NSError *error, NSString *errorMsg) {
NSLog(@"%@", error);
}];
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//请求完毕后的处理
});