Discover subclasses of a given class in Obj-C

cocoa, objective-c, reflection

Solution

Rather than try to automatically register all the subclasses of `MYCommand`, why not split the problem in two?

First, provide API for registering a class, something like `+[MYCommand registerClass:]`.

Then, create code in MYCommand that means any subclasses will automatically register themselves. Something like:

@implementation MYCommand
+ (void)load
{
    [MYCommand registerClass:self];
}
@end

Problem

Is there any way to discover at runtime which subclasses exist of a given class? Edit: From the answers so far I think I need to clarify a bit more what I am trying to do. I am aware that this is not a common practice in Cocoa, and that it may come with some caveats. I am writing a parser using the dynamic creation pattern. (See the book Cocoa Design Patterns by Buck and Yacktman, chapter 5.) Basically, the parser instance processes a stack, and instantiates objects that know how to perform certain calculations. If I can get all the subclasses of the `MYCommand` class, I can, for example, provide the user with a list of available commands. Also, in the example from chapter 5, the parser has an substitution dictionary so operators like +, -, * and / can be used. (They are mapped to `MYAddCommand`, etc.) To me it seemed this information belonged in the `MyCommand` subclass, not the parser instance as it kinda defeats the idea of dynamic creation.

Original source