Traverse a class hierarchy from base to all descendants

故事扮演 提交于 2019-11-30 16:06:13

问题


In an iOS app I am writing I want to traverse a class hierarchy to make an inventory of all subclasses. My intent is to use each subclass type as a key -- via NSStringForClass() -- in a dictionary.

My motivation is to be able to automatically discover all variants of a base class so that I can call methods associated with that class. For reasons of division of labor I prefer not to use method overriding here.

Is it possible to do such a traversal? How would it work?


回答1:


Here's an example. This method will return all subclasses descending from the class you send the message 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

Modify it as needed, make recursive calls, etc.



来源:https://stackoverflow.com/questions/9587829/traverse-a-class-hierarchy-from-base-to-all-descendants

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!