将是巨大的,如果目标C有承诺,但在那之前,我通常处理这样的事情递归,使用输入数组作为一个待办事项列表...
- (void)doThingToArray:(NSArray *)array then:(void (^)(void))completion {
NSInteger count = array.count;
// bonus feature: this recursive method calls its block when all things are done
if (!count) return completion();
id firstThing = array[0];
// this is your original method here...
[self doThingToObject:firstThing complete:^{
NSArray *remainingThings = [array subarrayWithRange:NSMakeRange(1, count-1)];
[self doThingToArray:remainingThings then:completion];
}];
}
这工作正常短阵列。让我知道如果数组很大(数千个元素),我可以告诉你如何以不会结束堆栈的方式进行递归(通过使doThing
方法采用单个参数并使用performSelector“递归”)。
编辑 - 执行选择器让当前运行循环完成并在下一次将选择器排队。这样可以节省堆栈,因为您在长阵列上递归,但只需要一个参数,所以我们必须通过整合阵列并将参数阻塞到单个集合对象中来使得该方法稍微不可读...
- (void)doThingToArray2:(NSDictionary *)params {
NSArray *array = params[@"array"];
void (^completion)(void) = params[@"completion"];
NSInteger count = array.count;
// bonus feature: this recursive method calls its block when all things are done
if (!count) return completion();
id firstThing = array[0];
// this is your original method here...
[self doThingToObject:firstThing complete:^{
NSArray *remainingThings = [array subarrayWithRange:NSMakeRange(1, count-1)];
[self performSelector:@selector(doThingToArray2:)
withObject:@{@"array": remainingThings, @"completion": completion}
afterDelay:0];
}];
}
// call it like this:
NSArray *array = @[@1, @2, @3];
void (^completion)(void) = ^void(void) { NSLog(@"done"); };
[self doThingToArray2:@{@"array": array, @"completion": completion}];
// or wrap it in the original method, so callers don't have to fuss with the
// single dictionary param
- (void)doThingToArray:(NSArray *)array then:(void (^)(void))completion {
[self doThingToArray2:@{@"array": array, @"completion": completion}];
}
OP是否需要最后提到的方法,我很想看到它的快速草图。 – ravron 2014-11-08 23:58:56
@Riley - 当然。请参阅编辑。 – danh 2014-11-09 01:05:41