需求: 从三个网络请求中拿到数据后才能刷新页面?
使用线程组
dispatch_group_t group = dispatch_group_create();
// data1
dispatch_group_enter(group);
[NetworkAPI getData1WithCompletionHandler:^(id obj) {
self.data1 = obj;
dispatch_group_leave(group);
}errorHandler:^(NSError*error) {
dispatch_group_leave(group);
}];
// data2
dispatch_group_enter(group);
[NetworkAPI getData2WithCompletionHandler:^(id obj) {
self.data2 = obj;
dispatch_group_leave(group);
}errorHandler:^(NSError*error) {
dispatch_group_leave(group);
}];
// data3
dispatch_group_enter(group);
[NetworkAPI getData3WithCompletionHandler:^(id obj) {
self.data3 = obj;
dispatch_group_leave(group);
}errorHandler:^(NSError*error) {
dispatch_group_leave(group);
}];
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
self.view.data = @[self.data1, self.data2, self.data3];
});
dispatch_group_enter会对group的内部计数加一,dispatch_group_leave会对group的内部计数减一,就类似以前的retain和release方法。说白了也是维护了一个计数器。
网友评论