Dispatch_Group使用笔记

一、异步请求

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();

    __block NSDictionary *firstResponse;
    __block NSDictionary *secondResponse;
    __block GmacsError *firstError;
    __block GmacsError *secondError;
    
    //
    dispatch_group_enter(group);
    [NetManager requestWithBlock:^(NSDictionary *response, GmacsError *error) {
            if (error && error.code != 0) {
                firstResponse = nil;
                firstError = error;
            }else{
                firstResponse = response;
                firstError = nil;
            }
            //
            dispatch_group_leave(group);
     }];
    //
    dispatch_group_enter(group);
    [NetManager requestWithBlock:^(NSDictionary *response, GmacsError *error) {
            if (error && error.code != 0) {
                secondResponse = nil;
                secondError = error;
            }else{
                secondResponse = response;
                secondError = nil;
            }
            //
            dispatch_group_leave(group);
    }];
    
    //
    dispatch_group_notify(group, queue, ^{
        NSLog(@"[=== >] group dispatch_group_notify");
        if (firstError && firstError.code != 0) {
            firstError.msg = [NSString stringWithFormat:@"firstError:%@", firstError.msg];
            block(nil, nil, firstError);
        }else if (secondError && secondError.code != 0) {
            secondError.msg = [NSString stringWithFormat:@"secondError:%@", secondError.msg];
            block(nil, nil, secondError);
        }else{
            block(firstResponse, secondResponse, nil);
        }
    });

二、同步方法

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();

    __block NSDictionary *firstResponse;
    __block NSDictionary *secondResponse;
    
  dispatch_group_async(group, queue, ^{
        firstResponse = [NetManager requestWithParam:param];
});

  dispatch_group_async(group, queue, ^{
        secondResponse = [NetManager requestWithParam:param];
});
    //
    dispatch_group_notify(group, queue, ^{
        NSLog(@"[=== >] group dispatch_group_notify %@ %@", firstResponse, secondResponse);
    });

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容