Objective-C指向实现协议的类的指针

栏目: C · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/2664468/objective-c-pointer-to-class-that-implements-a-protocol

我有三个实现相同协议的类,并且具有不实现协议的相同父类.通常我会将协议作为父类中的纯虚函数,但我找不到Objective-C方法来做到这一点.

我想通过在超类中声明纯虚函数然后让子实现这些函数来利用这些子类的多态性.然而,我发现这样做的唯一Objective-C方法是让每个孩子明确决定实现一个协议,当我这样做时,超类不知道孩子们会实现该协议,所以有编译时警告到处都是.

一些伪代码如果没有意义:

@interface superclass: NSObject
{}

@interface child1: superclass<MyProtocol>
{}

@interface child2: superclass<MyProtocol>
{}

这些类的消费者:

@class child1
@class child2
@class superclass

@interface SomeViewController: UIViewController
{
    child1 *oneView;
    child2 *otherView;
    superclass *currentView;
}

-(void) someMethod
{
    [currentView protocolFunction];
}

我发现在Objective-C中执行纯虚函数的唯一好方法就是放入[self doesNotRecognizeSelector:_cmd];在父类中,但它不理想,因为它会导致运行时错误而不是编译时间.

Objective-C开发人员通常在这些情况下使用动态检查而不是编译时检查,因为语言和框架很好地支持它.例如,您可以像这样编写方法:
- (void)someMethod
{
    // See if the object in currentView conforms to MyProtocol
    //
    if ([currentView conformsToProtocol:@protocol(MyProtocol)])
    {
        // Cast currentView to the protocol, since we checked to make
        // sure it conforms to it. This keeps the compiler happy.
        //
        [(SuperClass<MyProtocol> *) currentView protocolMethod];
    }
}

翻译自:https://stackoverflow.com/questions/2664468/objective-c-pointer-to-class-that-implements-a-protocol


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

High-Performance Compilers for Parallel Computing

High-Performance Compilers for Parallel Computing

Michael Wolfe / Addison-Wesley / 1995-6-16 / USD 117.40

By the author of the classic 1989 monograph, Optimizing Supercompilers for Supercomputers, this book covers the knowledge and skills necessary to build a competitive, advanced compiler for parallel or......一起来看看 《High-Performance Compilers for Parallel Computing》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

随机密码生成器
随机密码生成器

多种字符组合密码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具