views:

32

answers:

1

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?

+2  A: 

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.

Jon Steinmetz
Thanks for that info, do you know where I can find a reference for Class? I've been scouring the net trying to find some documentation- and Apple's reference docs aren't exactly helpful compared with something more navigable like JavaDoc.
Sophistifunk
The Apple Objective C manual talks a little about how classes are objects but not in great detail, http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/ObjC.pdf. Many of the class methods in NSObject should be able to be called but only some make sense. http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html. Otherwise I have not yet found a good synopsis of how to interact with a Class object.
Jon Steinmetz
This discussion is interesting but is a little abstract as well, http://cocoawithlove.com/2010/01/what-is-meta-class-in-objective-c.html.
Jon Steinmetz