How can I force a protocol to be linked in a library when no class in the library adopts it?

125 views Asked by At

It appears that if I declare an Objective-C protocol in a project but no classes in the project/target actually adopt the protocol, the runtime doesn't know about the protocol at runtime. (i.e. NSProtocolFromString(@"MyProtocol") returns NULL) However, if I add a minimal "dummy" class, like this:

@interface Dummy : NSObject < MyProtocol >
@end
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wprotocol"
@implementation Dummy
@end
#pragma clang diagnostic pop

...the runtime will know about the existence of the protocol at runtime.

Is there a more elegant/less-hacky way to ensure that an otherwise-unadopted protocol will be "known" at runtime?

1

There are 1 answers

1
simple_code On

Try @protocol(MyProtocol) instead of NSProtocolFromString(@"MyProtocol"). I found it near the bottom of this page http://nshipster.com/at-compiler-directives/. Does that help answer the question?