Let’s say I have a method that takes a class, which is called like so:
[registry registerClass:[MyClass class]];
How do I interrogate the class inside -registerClass:?
-(void) registerClass:(Class)typeClass {
// Verify that instances of typeClass confirm to protocol / respondsToSelector
// ?
// Do stuff
// ...
[myListOfClasses addObject:typeClass];
// ...
}
It’s the “?” I’m wondering about. Can I safely (and always) cast Class foo to NSObject *fooObj and send it messages, assuming foo will always be a subclass of NSObject? Is there a root metaclass that all NSObject metaclasses inherit from? Or are all Class objects simply instances of a single metaclass?
The type Class is also an object and can have methods called on it. Listing 5 in this Apple example shows some examples of methods that can be called on a Class object.
Specifically you can call conformsToProtocol: on the class object such as:
Or you can use instancesRespondToSelector: to see if instances of this class implement the selector.
Be aware that calling respondsToSelector: on the Class object will test for class methods that the class implements and not instance methods for the class.