我有一长串需要在我的Objective-C代码中发生的事件。假设我有6件事 - thingA,thingB,thingC,thingD,thingE和thingF。thingB和thingD返回一个BOOL值。如果thingB是NO,则不需要调用thingC。如果thingD是NO,则不需要调用thingE。
- (void)doThings:(void(^)())completion {
[self thingA: ^{
[self thingB: ^(BOOL success) {
if (success) {
[self thingC: ^{
[self thingD: ^(BOOL success) {
if (thingD) {
[self thingE: ^{
[self thingF];
completion();
}];
return;
}
[self thingF];
completion();
}];
}];
return;
}
[self thingD: ^(BOOL success) {
if (success) {
[self thingE: ^{
[self thingF];
completion();
}];
return;
}
[self thingF];
completion();
}];
}];
}];
}
这可能很快变得难以处理。你可以将那些有不同结果但会重新回到循环中的事情分离出来,并将它们制作成新的方法,如下所示:
- (void)doThings:(void(^)())completion {
[self thingA: ^{
[self attemptThingB: ^{
[self attemptThingD: ^{
[self thingF];
completion();
}]
}];
}]
}
- (void)attemptThingB:(void(^)())completion {
[self thingB: ^(BOOL success) {
if (success) {
[self thingC: {
completion();
}];
return;
}
completion();
}];
}
- (void)attemptThingD:(void(^)())completion {
[self thingD: ^(BOOL success) {
if (success) {
[self thingE: ^{
completion();
}];
return;
}
completion();
}];
}
这样可以减少代码的重复,但仍然杂乱无章且难以跟踪。甚至会导致带有尴尬名称的方法,这些方法实际上只是针对特定情况的辅助方法。
一定有更好的方法。一种看起来非常类似于同步编码,但是异步的方法。上面的代码很难阅读,如果我想要添加新内容到流程中,那么它就会变得危险。
有更好的解决方案吗?类似于这样的东西?
- (void)doThings {
[self thingA];
BOOL thingBSuccess = [self thingB];
if (thingBSuccess == YES) {
[self thingC];
}
BOOL thingDSuccess = [self thingD];
if (thingDSuccess == YES) {
[self thingE];
}
[self thingF];
return;
}
那个提出的解决方案立刻显露出的问题是,完成处理程序可以传递多个对象,而块的返回值只能处理1个对象。但类似于这样的格式?它更加清晰易懂,易于维护。