Traverse the class hierarchy from base to all descendants
In an iOS app, I write that I want to traverse the class hierarchy to make an inventory of all subclasses. I intend to use each type of subclass as a key - via NSStringForClass()
- in the dictionary.
My motivation is to be able to automatically detect all variants of a base class so that I can call methods associated with that class. For division of labor reasons, I prefer not to use the override method here.
Is it possible to make such a detour? How it works?
+3
source to share
1 answer
Here's an example. This method returns all subclasses descended from the class you are posting to.
@interface NSObject (Debugging)
+ (NSArray *) allSubclasses;
@end
@implementation NSObject (Debugging)
+ (NSArray *) allSubclasses
{
Class myClass = [self class];
NSMutableArray *mySubclasses = [NSMutableArray array];
unsigned int numOfClasses;
Class *classes = objc_copyClassList(&numOfClasses);
for (unsigned int ci = 0; ci < numOfClasses; ci++) {
// Replace the code in this loop to limit the result to immediate subclasses:
// Class superClass = class_getSuperclass(classes[ci]);
// if (superClass == myClass)
// [mySubclasses addObject: classes[ci]];
Class superClass = classes[ci];
do {
superClass = class_getSuperclass(superClass);
} while (superClass && superClass != myClass);
if (superClass)
[mySubclasses addObject: classes[ci]];
}
free(classes);
return mySubclasses;
}
@end
Change it as needed, make recursive calls, etc.
+7
source to share