Implementing a method taking a block to use as cal

2019-01-04 22:31发布

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

}

3条回答
一纸荒年 Trace。
2楼-- · 2019-01-04 22:36

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

查看更多
甜甜的少女心
3楼-- · 2019-01-04 22:47

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);
    }
}
查看更多
虎瘦雄心在
4楼-- · 2019-01-04 22:53

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

查看更多
登录 后发表回答