2011-11-03 87 views
6

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

@protocol P1 

-(void) printP1; 

-(void) printCommon; 

@end 


@protocol P2 

-(void) printP2; 

-(void) printCommon; 
@end 

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

@interface TestProtocolImplementation : NSObject <P1,P2> 
{ 

} 

@end 

我如何编写方法实施“printCommon”。当我尝试执行我有编译时错误。

有没有可能为“printCommon”编写方法实现。

+0

你可以发布你的错误和你的实施? – jbat100

+0

的#pragma标记 - 的#pragma标记P1协议方法 - (无效)printP1 { \t的NSLog(@ “打印P1”); (无效)printCommon { \t NSLog(@“Print P1”); } 的#pragma马克 - 的#pragma标记P2协议方法 - (无效)printP2 { \t的NSLog(@ “打印P2”); (无效)printCommon { \t NSLog(@“Print P2”); \t } 错误:重新定义“ - [TestObjectLifeCycle printCommon]” 它是工作良好时我删除“printCommon”方法的实现中的任何一个。 – selva

回答

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 

现在其采用P1P2也必须采用PrintCommon的方法,以便类型完成采用,并且您可以安全地通过NSObject<P1>*NSObject<PrintCommon>*参数。

2

对我来说,下面的代码没有工作:

@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 

编译器用户:苹果LLVM 3.0 但是,如果你设计这样一个解决方案,尽量避免这种情况。

相关问题