如何在类实现中区分两个协议的相同方法名称?

sel*_*lva 7 oop protocols objective-c ios5

我有两个协议

@protocol P1

-(void) printP1;

-(void) printCommon;

@end


@protocol P2

-(void) printP2;

-(void) printCommon;
@end
Run Code Online (Sandbox Code Playgroud)

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

@interface TestProtocolImplementation : NSObject <P1,P2>
{

}

@end
Run Code Online (Sandbox Code Playgroud)

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

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

jus*_*tin 14

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

@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
Run Code Online (Sandbox Code Playgroud)

现在类型的采用P1P2也必须采用PrintCommon,以满足采用的方法,你可以安全地传递一个NSObject<P1>*通过NSObject<PrintCommon>*参数.