内容简介:翻译自: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];在父类中,但它不理想,因为它会导致运行时错误而不是编译时间.
- (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
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Is Parallel Programming Hard, And, If So, What Can You Do About
Paul E. McKenney
The purpose of this book is to help you understand how to program shared-memory parallel machines without risking your sanity.1 By describing the algorithms and designs that have worked well in the pa......一起来看看 《Is Parallel Programming Hard, And, If So, What Can You Do About 》 这本书的介绍吧!