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

你可能感兴趣的:(Dispatch_Group使用笔记)