Implementing a method taking a block to use as callback

Chris picture Chris · Aug 24, 2011 · Viewed 41.6k times · Source

I would like to write a method similar to this:

+(void)myMethodWithView:(UIView *)exampleView completion:(void (^)(BOOL finished))completion;

I've basically stripped down the syntax taken from one of Apple's class methods for UIView:

+ (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion;

And would expect it to be used like so:

[myFoo myMethodWithView:self.view completion:^(BOOL finished){
                     NSLog(@"call back success");
                 }];

My question is how can I implement this? If someone can point me to the correct documentation that would be great, and a very basic example would be much appreciated (or a similar answer on Stack Overflow -- I couldn't find one). I still don't quite know enough about delegates to determine whether that is even the correct approach!

I've put a rough example of what I would have expected it to be in the implementation file, but as I can't find info it's guess work.

+ (void)myMethod:(UIView *)exampleView completion:(void (^)(BOOL finished))completion {
    // do stuff

    if (completion) {
        // what sort of syntax goes here? If I've constructed this correctly!
    }

}

Answer

omz picture omz · Aug 24, 2011

You can call a block like a regular function:

BOOL finished = ...;
if (completion) {
    completion(finished);
}

So that means implementing a complete block function using your example would look like this:

+ (void)myMethod:(UIView *)exampleView completion:(void (^)(BOOL finished))completion {
    if (completion) {
        completion(finished);
    }
}