Devfly
Devfly

Reputation: 2495

Execute a piece of code in block after the block is executed

My method have a block called completionBlock. I want inside my function that calls completionBlock() to add a piece of code that's going to execute after this completionBlock has been executed.

Something like a completionBlock of the super block.

Of course I can do it on the bottom in the actual block, but I'm using it in lots of places and it would be troublesome.

Thanks!

Upvotes: 0

Views: 80

Answers (1)

rob mayoff
rob mayoff

Reputation: 385500

Just create a new block that calls completionBlock and then runs your extra code. Use the new block as the completion block.

Example:

- (void)animateDownWithCompletion:(void (^)(BOOL finished))completion {
    [UIView animateWithDuration:1 animations:^{
        CGPoint center = self.view.center;
        center.y += 10;
        self.view.center = center;
    } completion:^(BOOL finished) {
        if (completion) {
            completion(finished);
        }
        NSLog(@"more completion code here!");
    }];
}

Or with variables:

void (^originalCompletionBlock)(BOOL finished) = ...;

void (^newCompletionBlock)(BOOL finished) = ^(BOOL finished) {
    if (originalCompletionBlock) {
        originalCompletionBlock(finished);
    }
    NSLog(@"more completion code here!");
};

Upvotes: 1

Related Questions