Objective-C编译器省略了协议定义

时间:2014-02-07 01:56:09

标签: ios objective-c protocols llvm objective-c-runtime

我正在编写一些使用Objective-C运行时库的类。这包括在运行时根据名称检索协议定义。但是,似乎未通过类显式采用或使用@protocol(ProtocolName)在代码中引用的协议将从编译中排除,并且在运行时不可用。

示例:

@protocol MyProtocol <NSObject>

-(void)doSomething;

@end

//代码中的其他地方

Protocol *protocol = NSProtocolFromString(@"MyProtocol"); 
// ^ value of "protocol" will be nil when I run the application!

//但是,如果我使用,请执行以下操作:

Protocol *whyDoIHaveToDoThis = @protocol(MyProtocol);
Protocol *protocol = NSProtocolFromString(@"MyProtocol"); 
// ^ value of "protocol" will now be a pointer as expected when I run the application!

有谁知道为什么会这样,甚至更好,如何强制编译器包含在编译时未使用的协议定义,但后来我想在运行时使用它?

1 个答案:

答案 0 :(得分:3)

您可以通过创建一个未使用它的虚拟方法来强制编译器包含协议。我之前做过这个:

void preserveProtocolFromBeingTrimmed()
{
     (void)@protocol(BrightnessProtocol);
}

我看到Apple在FxBrightness plug-in from the FxPlug SDK中使用了这个。

相关问题