我正在编写几个使用 Objective-C 运行时库的类。这包括在运行时根据名称检索协议(protocol)定义。但是,似乎没有被类明确采用或在代码中使用@protocol(ProtocolName) 引用的协议(protocol)被排除在编译之外,并且在运行时不可用。
例子:
@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!
有谁知道这是为什么,甚至更好的是如何强制编译器包含在编译时未使用但我稍后希望在运行时可用的协议(protocol)定义?
最佳答案
您可以通过创建一个未调用的使用它的虚拟方法来强制编译器包含该协议(protocol)。我以前做过这个:
void preserveProtocolFromBeingTrimmed()
{
(void)@protocol(BrightnessProtocol);
}
我看到苹果在他们的 FxBrightness plug-in from the FxPlug SDK 中使用了这个。
关于ios - Objective-C 编译器遗漏了协议(protocol)定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21617871/