【问题标题】:Is possible to pass custom code to method in protocol? [duplicate]是否可以将自定义代码传递给协议中的方法? [复制]
【发布时间】:2014-11-12 06:51:55
【问题描述】:

是否可以在 obj-c 中将一些自定义代码传递给协议中的方法,而无需为此创建新类?我花了一些时间在 Java 上,像下面这样的东西很舒服

interface TestInterface {
    void onTest();
}

class testClass{
    void main {
        TestInterface test = new TestInterface(){
            @Override
            void onTest(){
                // some custom code
            }
        };

        someTestMethod(test);
    }

    private someTestMethod(TestInterface pDelegate){
        if (pDelegate != null){
            pDelegate.onTest();
        }
    }
}

基本上可以初始化协议变量并覆盖它的方法吗?

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

    尝试使用块,如下所示:

    @implementation TestObject
    
    - (void)run {
        [self someTestMethodWithBlock:^{
            // some test code
        }];
    }
    
    - (void)someTestMethodWithBlock:(void (^)(void))block {
        if (block != nil) {
            block();
        }
    }
    
    @end
    

    如果您在您最喜欢的搜索引擎中输入“objective-c blocks”,您可以找到更多信息,包括教程。

    【讨论】:

    • 谢谢,我知道块,但我很好奇它是否像在 java 中那样可行。
    猜你喜欢
    • 1970-01-01
    • 2019-02-15
    • 2013-05-07
    • 2015-01-23
    • 1970-01-01
    • 2021-05-08
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多