Objective C : Given a Class id, can I check if this class implements a certain protocol? Or has a certain selector?

Jacko picture Jacko · Feb 26, 2010 · Viewed 21k times · Source

I want to use this for an object factory: Given a string, create a Class, and if this Class supports a protocol (with a Create() method) then alloc the class and call Create.

Answer

Chuck picture Chuck · Feb 26, 2010
NSString *className; //assume this exists
Class class = NSClassFromString(className);
if ([class conformsToProtocol:@protocol(SomeProtocol)]) {
    id instance = [[class alloc] init];
    [instance create];
}