iOS开发iOS点点滴滴

GCD group 用法 and 项目实践

2016-01-09  本文已影响695人  一铭_

在dispatch_queue中所有的任务执行完成后在做某种操作,这个需求在项目中非常常见,但是在并行队列中怎么处理,尤其是多个网络请求,那就用dispatch_group 成组操作:
项目背景:
一个 tableView 的两个 section 需要不同网络接口,而且必须要等到两个网络请求结束后再创建 tableView(类似的需求在项目中不要太多)

//第一步
dispatch_group_t dispatchGroup = dispatch_group_create();
dispatch_group_enter(dispatchGroup);
//enter方法显示的是group中的任务未执行完毕的任务数目加1,这种方式用在不使用dispatch_group_async来提交任务,要配合使用,有enter要有leave,这样才能保证功能完整实现。

//第二步
[AFNTool requestWithUrlString:@"xxxxxxx" params:dic success:^(NSDictionary *success) {
      //在这里处理你的数据, do what you want
      //这里的 leave 就是配合上面的 enter 来搭配使用
        dispatch_group_leave(dispatchGroup);
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
      //失败也要 leave, enter和 leave 一定要成对 
        dispatch_group_leave(dispatchGroup);
    }];

接下来写第二个网络请求

dispatch_group_enter(dispatchGroup);
[AFNTool requestWithUrlString:@"xxxxxx" params:dict success:^(NSDictionary *success) {
// do something
//配合上面的 enter ,一个 enter 一个 leave
        dispatch_group_leave(dispatchGroup);
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        dispatch_group_leave(dispatchGroup);
  }];

为group设置通知一个block,当group关联的block执行完毕后,就调用这个block。


dispatch_group_notify(group, dispatch_get_main_queue(), ^{**
  // 在主线程处理 UI
}); 

大概就是这样,挺好用的,可以多试试

上一篇 下一篇

猜你喜欢

热点阅读