实现一个使用块作为回调的方法 [英] Implementing a method taking a block to use as callback

查看:113
本文介绍了实现一个使用块作为回调的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个类似下面的方法:

I would like to write a method similar to this:

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

我已经基本剥夺了一个Apple的类方法 UIView

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

我的问题是如何实现这个?如果有人可以指向正确的文档,这将是巨大的,一个非常基本的例子将是非常感谢(或Stack Overflow类似的答案 - 我找不到一个)。我仍然不够了解代表,以确定是否是正确的方法!

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

}


推荐答案

可以像常规函数一样调用块:

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

这篇关于实现一个使用块作为回调的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆