【问题标题】:How can I differentiate the same method name of two protocols in a class implementation?如何区分类实现中两个协议的相同方法名称?
【发布时间】:2011-11-03 09:07:21
【问题描述】:

我有两个协议

@protocol P1

-(void) printP1;

-(void) printCommon;

@end


@protocol P2

-(void) printP2;

-(void) printCommon;
@end

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

@interface TestProtocolImplementation : NSObject <P1,P2>
{

}

@end

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

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

【问题讨论】:

  • 你能发布你的错误和你的实现吗?
  • #pragma mark - #pragma mark P1 协议方法 -(void)printP1 { NSLog(@"print p1"); } -(void) printCommon { NSLog(@"Print P1"); } #pragma mark - #pragma mark P2 协议方法 -(void)printP2 { NSLog(@"print p2"); } -(void) printCommon { NSLog(@"Print P2");错误:重新定义'-[TestObjectLifeCycle printCommon]' 当我删除任何一个“printCommon”方法实现时,它运行良好。

标签: objective-c oop ios5 protocols


【解决方案1】:

常见的解决方案是将通用协议分离出来,让派生的协议实现通用协议,如下:

@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&lt;PrintCommon&gt;* 参数传递NSObject&lt;P1&gt;*

【讨论】:

    【解决方案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
    

    编译器用户:Apple LLVM 3.0 但如果您正在设计这样的解决方案,请尽量避免此类情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2015-03-11
      • 2011-07-26
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多