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.
Objective C : Given a Class id, can I check if this class implements a certain protocol? Or has a certain selector?
21.9k Views Asked by Jacko At
2
May I, however, point out just how many awful Objective-C rules you're breaking by doing the above? For example, you should never be calling methods on an allocated-but-not-initialized instance. The Xcode Static Analyzer will give you all sorts of warnings about memory leaks.
A better option would be this:
But you seem to imply that you don't want to call init.
You could consider a class method:
[klass create]
, which would return a non-owned instance ofklass
. Then you'd just check[klass respondsToSelector:@selector(create)]
before calling it.