GCD and blocks are so nice and convenient. But when I fall in love with it, I found that something bad happened. Look at these codes below:
[self functionA:^(BOOL success) {
if (success) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
[self functionB:^(NSError *error) {
if (error != nil) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
[self functionC:^(id result) {
if (result) {
[self functionD:^(BOOL success) {
if (success) {
[self DoSomething];
}
}];
}
}];
});
}
}];
});
}
}];
Crazy? Yes. I am in this trouble.
Did someone have any experience avoiding nested blocks like this?
Edited:
Thanks guys. Exactly, we have more elegant ways to do this. Such as:
- Declare blocks beforehand
- Make sub blocks as independent function
But what I expect is a general solution. Maybe like this:(Pseudo code below)
functionA.flat.success = [self functionB];
functionB.flat.isntnil = [self functionC];
functionB.flat.error = {};
functionC.flat.isntnil = [self functionD];
[flat call:functionA];