How do I interrogate a Class in a typesafe way?
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 messa开发者_如何学运维ges, 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:
[ typeClass conformsToProtocol: @protocol( MyProtocol ) ];
Or you can use instancesRespondToSelector: to see if instances of this class implement the selector.
[ typeClass instancesRespondToSelector: @selector( MyNeatMethod ) ];
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.
精彩评论