简体   繁体   中英

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!

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!");
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM