How would you perform N asynchronous operations, such as network calls, working with completion block operations and no delegates/notifications?
Given N methods like this:
- (void)methodNWithCompletion:(void (^)(Result *))completion {
Operation *operation = [Operation new];
// ...
// Asynchronous operation performed here
// ...
return;
}
A straightforward solution would be to call each operation in the completion block of the previous one:
[self method1WithCompletion:^(Result *result) {
// ...
[self method2WithCompletion:^(Result *result) {
// ...
[self method3WithCompletion:^(Result *result) {
// ...
[self method4WithCompletion:^(Result *result) {
NSLog(@"All done");
}
}
}
}
but I'm looking for a more elegant and reusable solution, easier to write and maintain (with no many indented blocks).
Many thanks, DAN
dispatch_group. So, enter the group before doing each asynchronous call, exit the group in the completion handler of the asynchronous call, and then configure adispatch_group_notifyto be performed when all of the asynchronous calls are done. E.g., stackoverflow.com/a/29716069/1271826 or stackoverflow.com/a/34532865/1271826.