Luke The Obscure
Luke The Obscure

Reputation: 1524

Passing a block to a block in iOS

I'm trying to create a wrapper method that accepts a completion handler block, which in turn gets passed to another completion handler. The problem is, no matter what I do my completion handler gets deallocated before it gets called. Here's the method with the most of logic stripped out.

+ (int) syncWithCompletion:(void (^)(NSError *error))completion;{
    //Copy the block argument and make it available to the block scope
    __block void (^completionBlock)(NSError *error) = [completion copy];
    // The is an AFNetworking operation
    [af.sharedHTTPClient enqueueBatchOfHTTPRequestOperations:syncOperations progressBlock:nil completionBlock:^(NSArray *operations) {
        // Call my copied block... but it's already been deallocated
        completionBlock(error);
    }];
    return somevariable;
}

Upvotes: 0

Views: 68

Answers (1)

Luke The Obscure
Luke The Obscure

Reputation: 1524

bah... Code was dying from another call to the function where the completion handler was nil. This fixed it:

if(completionBlock){
    completionBlock(error);
}

Upvotes: 1

Related Questions