Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a method taking a block to use as callback

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

}
like image 820
Chris Avatar asked Aug 24 '11 18:08

Chris


3 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);
    }
}
like image 135
omz Avatar answered Nov 09 '22 00:11

omz


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

like image 34
Chaitanya Gupta Avatar answered Nov 08 '22 22:11

Chaitanya Gupta


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

like image 1
Mohammad Abdurraafay Avatar answered Nov 09 '22 00:11

Mohammad Abdurraafay