【发布时间】:2014-08-10 12:37:22
【问题描述】:
我的 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 个对象。但是格式与此类似的东西?它非常清洁且易于维护。
【问题讨论】:
标签: ios objective-c asynchronous objective-c-blocks