【问题标题】:Calling a method defined in a protocol on a class included with forward declaration在前向声明中包含的类上调用协议中定义的方法
【发布时间】:2014-07-02 14:51:00
【问题描述】:

有没有办法告诉编译器非导入类(即前向声明)遵守协议?

在下面的示例中,我想在类 ForwardClass 上调用方法 foo。该类遵循MyProtocol 协议,但编译器不会知道这一点,因为使用了前向声明。

@protocol MyProtocol <NSObject>

+ (void) foo;

@end


@class ForwardClass; // <-- Forward declaration

@implementation MyClass

- (void) bar
{
    [ForwardClass foo]; // <-- This doesn't work!
}


我希望的是在像这样声明类的同时应用协议:

@class ForwardClass <MyProtocol>

或者在调用方法时以某种方式使用协议:

[ForwardClass<MyProtocol> foo]; 


这并不是一个真正的大问题,因为我可以直接导入类,但如果它可以工作,那就太好了,因为我只需要导入协议,而不是整个类。

【问题讨论】:

  • 首先,你的协议声明了实例方法,而不是类方法。
  • @Kreiri 我的错,当然应该是一个类方法。已编辑。

标签: objective-c protocols forward-declaration


【解决方案1】:

没有。前向声明适用于您需要知道类类型但不需要知道其具体实现(例如属性和方法)的情况。在您的情况下,您确实关心它实现的方法,因此您需要为 ForwardClass 引入标头。

【讨论】:

    【解决方案2】:

    你可以的

    Class x = NSClassFromString(@"ForwardClass");
    [x foo];
    

    但没那么好看

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多