Search code examples
iosobjective-crecursionblock

Recursive Methods with completion blocks


I call my method:

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

the method:

-(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();
}

}

I get the "else statement fields:" log, but the "completionBlock Fields:" never runs.

I'm guessing it has to do with a retain issue; that the original method that calls this recursive loop is de-referenced so when the completionBlock is called, the code is gone.

How can I prevent this?


Solution

  • The block is running, but the recursive calls to the method are passing ^{}, an empty block. Fix by passing the original block parameter...

    -(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();
        }
    }