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

Win*_*der 7 polymorphism objective-c

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

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

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

@interface superclass: NSObject
{}

@interface child1: superclass<MyProtocol>
{}

@interface child2: superclass<MyProtocol>
{}
Run Code Online (Sandbox Code Playgroud)

这些类的消费者:

@class child1
@class child2
@class superclass

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

-(void) someMethod
{
    [currentView protocolFunction];
}
Run Code Online (Sandbox Code Playgroud)

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

jle*_*ehr 11

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];
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 当然,使用`respondsToSelector:@selector(protocolMethod)`更可靠. (3认同)
  • ......如果协议有可选方法,则必要. (2认同)

Win*_*der 5

通过使superclass *currentView属性看起来像这样,我能够让编译器正确警告我:

@property (nonatomic, retain) superclass<MyProtocol> *currentView;
Run Code Online (Sandbox Code Playgroud)