Home » Ios » Implementing a method taking a block to use as callback

Implementing a method taking a block to use as callback

Posted by: admin November 30, 2017 Leave a comment

Questions:

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!
    }

}
Answers:

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

Questions:
Answers:

I would highly recommend that you read up on Blocks to understand what is happening.

Questions:
Answers:

If you’re specially looking for a doc, to create custom method using blocks, then the following link is the one which explains almost everything about it. 🙂

http://developer.apple.com/library/ios/documentation/cocoa/Conceptual/Blocks/Articles/bxUsing.html

I happen to answer quite a same question recently, have a look at this: Declare a block method parameter without using a typedef