Wait until multiple networking requests have all executed - including their completion blocks

后端 未结 4 1122
攒了一身酷
攒了一身酷 2020-11-27 10:33

I have multiple operations (they\'re AFNetworking requests) with completion blocks that takes some time to execute, and a Core Data object that needs to be saved at the end

4条回答
  •  自闭症患者
    2020-11-27 10:57

    Use dispatch groups.

    dispatch_group_t group = dispatch_group_create();
    
    MyCoreDataObject *coreDataObject;
    
    dispatch_group_enter(group);
    AFHTTPRequestOperation *operation1 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
    [operation1 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        coreDataObject.attribute1 = responseObject;
        sleep(5);
        dispatch_group_leave(group);
    }];
    [operation1 start];
    
    dispatch_group_enter(group);
    AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
    [operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        coreDataObject.attribute2 = responseObject;
        sleep(10);
        dispatch_group_leave(group);
    }];
    [operation2 start];
    
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    dispatch_release(group);
    
    [context save:nil];
    

提交回复
热议问题