本文介绍了如何在类实现中区分两个协议的相同方法名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个协议

@protocol P1

-(void) printP1;

-(void) printCommon;

@end


@protocol P2

-(void) printP2;

-(void) printCommon;
@end

现在,我在一个类中实现这两个协议

Now, I am implementing these two protocols in one class

@interface TestProtocolImplementation : NSObject <P1,P2>
{

}

@end

我如何为printCommon编写方法实现。当我尝试执行时,我有编译时错误。

How can i write method implementation for "printCommon". When i try to do implementation i have compile time error.

是否有可能为printCommon编写方法实现。

Is there any possibility to write method implementation for "printCommon".

推荐答案

常见的解决方案是分离公共协议并使派生协议实现通用协议,如下所示:

The common solution is to separate the common protocol and make the derived protocols implement the common protocol, like so:

@protocol PrintCommon

-(void) printCommon;

@end

@protocol P1 < PrintCommon > // << a protocol which declares adoption to a protocol

-(void) printP1;

// -(void) printCommon; << available via PrintCommon

@end


@protocol P2 < PrintCommon >

-(void) printP2;

@end

现在采用 P1的类型 P2 还必须采用 PrintCommon 的方法才能完成采用,而你可以通过 NSObject< PrintCommon> * 参数安全地传递 NSObject< P1> *

Now types which adopt P1 and P2 must also adopt PrintCommon's methods in order to fulfill adoption, and you may safely pass an NSObject<P1>* through NSObject<PrintCommon>* parameters.

这篇关于如何在类实现中区分两个协议的相同方法名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-18 18:12