本文通过模拟当前流行的网络框架AFNetworking的使用,来演示手动管理GCD调度组的过程。
代码:
AFHTTPRequestOperationManager.h:
#import <Foundation/Foundation.h> @interface AFHTTPRequestOperationManager : NSObject + (instancetype)manager; - (void)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)())success failure:(void (^)())failure; @end
AFHTTPRequestOperationManager.m:
#import "AFHTTPRequestOperationManager.h" @implementation AFHTTPRequestOperationManager + (instancetype)manager { return [[self alloc] init]; } - (void)GET:(NSString *)URLString parameters:(id)parameters success:(void(^)())success failure:(void(^)())failure { NSUInteger duration = arc4random_uniform(5) + 1; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ success(); }); } @end
ViewController.m:
#import "ViewController.h" #import "AFHTTPRequestOperationManager.h" @interface ViewController () @property (strong, nonatomic) dispatch_group_t group; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; dispatch_group_enter(self.group); [manager GET:nil parameters:nil success:^{ NSLog(@"A done."); dispatch_group_leave(self.group); } failure:nil]; dispatch_group_enter(self.group); [manager GET:nil parameters:nil success:^{ NSLog(@"B done."); dispatch_group_leave(self.group); } failure:nil]; dispatch_group_enter(self.group); [manager GET:nil parameters:nil success:^{ NSLog(@"C done."); dispatch_group_leave(self.group); } failure:nil]; dispatch_group_enter(self.group); [manager GET:nil parameters:nil success:^{ NSLog(@"D done."); dispatch_group_leave(self.group); } failure:nil]; dispatch_group_enter(self.group); [manager GET:nil parameters:nil success:^{ NSLog(@"E done."); dispatch_group_leave(self.group); } failure:nil]; dispatch_group_notify(self.group, dispatch_get_main_queue(), ^{ NSLog(@"All done."); }); } - (dispatch_group_t)group { if (!_group) { dispatch_group_t group = dispatch_group_create(); _group = group; } return _group; } @end
可能的输出:
D done.
A done.
C done.
E done.
B done.
All done.
备注:
dispatch_group_enter()与dispatch_group_leave()调用必须一一对应。