iOS dispatch_group_t 用法

相比于单一界面而言,往往我们只需要调用单个接口获取数据展示,但是当数据量很大,或者当多个模块掺杂的情况下,我们往往需要调用多个接口来获取数据,按照串行来说,会造成界面卡顿,造成用户体验差,而当我们开始使用group时,会大大提升页面速度.

例如:某个界面我需要调用4个接口来获取数据

[self getUrl:APIURL_IndexBanner parm:nil completed:^(NSDictionary *json) {
        };
    } failure:^(NSError *error) {
    } showHud:NO];
    
//  下面的图片列表
    [self getUrl:APIURL_IndexImages parm:nil completed:^(NSDictionary *json) {
    } failure:^(NSError *error) {
    } showHud:NO];
//    最新动态  最新投资
    [self getUrl:APIURL_IndexLatest parm:nil completed:^(NSDictionary *json) {
   
    }failure:^(NSError *error) {
    } showHud:NO];
//  特权标
  
    [self getUrl:APIURL_IndexSpecial parm:nil completed:^(NSDictionary *json) {
        
    } failure:^(NSError *error) {
    } showHud:NO];

不用我说, 大家觉得会不会慢?

dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    dispatch_group_enter(group);
    dispatch_group_enter(group);
    dispatch_group_enter(group);
//    广告
    [self getUrl:APIURL_IndexBanner parm:nil completed:^(NSDictionary *json) {
          dispatch_group_leave(group);
        };
    } failure:^(NSError *error) {
          dispatch_group_leave(group);
    } showHud:NO];
    
//  下面的图片列表
    [self getUrl:APIURL_IndexImages parm:nil completed:^(NSDictionary *json) {
          dispatch_group_leave(group);
    } failure:^(NSError *error) {
        dispatch_group_leave(group);
    } showHud:NO];
//    最新动态  最新投资
    [self getUrl:APIURL_IndexLatest parm:nil completed:^(NSDictionary *json) {
        dispatch_group_leave(group);
    }failure:^(NSError *error) {
        dispatch_group_leave(group);
    } showHud:NO];
//  特权标
  
    [self getUrl:APIURL_IndexSpecial parm:nil completed:^(NSDictionary *json) {
        dispatch_group_leave(group);
    } failure:^(NSError *error) {
        dispatch_group_leave(group);
    } showHud:NO];
    
    [self loadInvestCount:group];

值得一提的是,dispatch_group_enter 与 dispatch_group_leave 必须配套使用,一进一出

你可能感兴趣的:(iOS dispatch_group_t 用法)