GCD group 用法 and 项目实践

来源:互联网 发布:ubuntu怎么分区 编辑:程序博客网 时间:2024/06/07 21:43

在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);    }];

接下来写第二个网络请求

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);  }];

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

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

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

0 0
原创粉丝点击