Objective c 如何在类实现中区分两个协议的相同方法名?
我有两个协议Objective c 如何在类实现中区分两个协议的相同方法名?,objective-c,oop,ios5,protocols,Objective C,Oop,Ios5,Protocols,我有两个协议 @protocol P1 -(void) printP1; -(void) printCommon; @end @protocol P2 -(void) printP2; -(void) printCommon; @end 现在,我在一个类中实现这两个协议 @interface TestProtocolImplementation : NSObject <P1,P2> { } @end @interface TestProtocolImplemen
@protocol P1
-(void) printP1;
-(void) printCommon;
@end
@protocol P2
-(void) printP2;
-(void) printCommon;
@end
现在,我在一个类中实现这两个协议
@interface TestProtocolImplementation : NSObject <P1,P2>
{
}
@end
@interface TestProtocolImplementation:NSObject
{
}
@结束
如何为“printCommon”编写方法实现。当我尝试实现时,我有编译时错误
是否有可能为“printCommon”编写方法实现。常见的解决方案是分离公共协议,并使派生协议实现公共协议,如下所示:
@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
@protocol-printcomon
-(无效)打印公共文件;
@结束
@协议P1/对我来说,以下代码确实有效:
@protocol P1
- (void) method1;
@end
@protocol P2
- (void) method1;
- (void) method2;
@end
@interface C1 : NSObject<P1, P2>
@end
@implementation C1
- (void) method1
{
NSLog(@"method1");
}
- (void) method2
{
NSLog(@"method2");
}
@end
协议P1
-(无效)方法1;
@结束
@协议P2
-(无效)方法1;
-(无效)方法2;
@结束
@接口C1:NSObject
@结束
@实施C1
-(无效)方法1
{
NSLog(“方法1”);
}
-(无效)方法2
{
NSLog(“方法2”);
}
@结束
编译器用户:苹果LLVM 3.0
但是,如果您正在设计这样的解决方案,请尽量避免这种情况。您可以发布错误和实现吗?#pragma mark-#pragma mark P1协议方法-(void)printP1{NSLog(@“print P1”);}-(void)printcomon{NSLog(@“print P1”)}#pragma mark P2协议方法-(void)printP2{NSLog(@“print P2”)}-(void)printCommon{NSLog(@“Print P2”);}错误:重新定义“-[TestObjectLifeCycle printCommon]”删除任何一个“printCommon”方法实现时,它工作正常。