具有完成块的递归方法

时间:2017-03-30 17:08:57

标签: ios objective-c recursion block

我打电话给我的方法:

[self getBoundariesForFields:fields index:0 withCompletionBlock:^{
    DLog(@"completionBlock fields: %@", fields);
}];

方法:

-(void)getBoundariesForFields:(NSArray *)fields index:(NSInteger)index withCompletionBlock:(void(^)())completionBlock {

if (index < fields.count) {
    NSMutableDictionary *field = [fields objectAtIndex:index];

    [self getBoundariesForField:field withCompletionBlock:^{
        [self getBoundariesForFields:fields index:index + 1 withCompletionBlock:^{
        }];
    }];
}
else {
    DLog(@"else statement fields: %@", fields);
    completionBlock();
}

}

我得到“else statement fields:”日志,但“completionBlock Fields:”永远不会运行。

我猜它与保留问题有关;调用此递归循环的原始方法被取消引用,因此当调用completionBlock时,代码就消失了。

我该如何防止这种情况?

1 个答案:

答案 0 :(得分:3)

块正在运行,但对该方法的递归调用正在传递^{},一个空块。通过传递原始块参数修复...

-(void)getBoundariesForFields:(NSArray *)fields index:(NSInteger)index withCompletionBlock:(void(^)())completionBlock {

    if (index < fields.count) {
        NSMutableDictionary *field = [fields objectAtIndex:index];

        [self getBoundariesForField:field withCompletionBlock:^{
            // NOTICE change here...
            [self getBoundariesForFields:fields index:index + 1 withCompletionBlock:completionBlock];
        }];
    }  else {
        DLog(@"else statement fields: %@", fields);
        completionBlock();
    }
}