views:

332

answers:

4

Is it possible to get a list of all descendant classes of a particular class in objective-c?

Something like:

@interface A : NSObject @end

@interface B : A @end

@interface C : A @end

NSArray *descendants = [A allDescendants]; // descendants = [B, C]

+5  A: 

The only way I can think is to enumerate the entire list of classes in the runtime (obtained with objc_getClassList) and test each one for isKindOfClass:A.

This is likely the only solution because classes do not maintain links to their descendants (only to their superclass).

Matt Gallagher
A: 

Matt,

I understand what you're saying, and this is true in Java too, but at least in Java you can go through ALL classes in the classpath and compare to see if each one of them implement the given class/interface (via reflection). Can't you do this in objective-c land too?

gav.newalkar
A: 

Could you use the class member somehow? Calling [[A class] superclass] returns an instance of the Class class for self's superclass. I think that you can get the name of a class from its Class - would that do what you want?

This doesn't really handle Protocols at all, but maybe this will point you in the right direction at least.

Andy
+1  A: 

As an example I am linking to solution by Ken Ferry to a Wil Shipley blog post.

Essentially, walking the classes.

Abizern