Traverse a class hierarchy from base to all descendants

前端 未结 1 838
后悔当初
后悔当初 2021-01-03 09:49

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 NSString

相关标签:
1条回答
  • 2021-01-03 10:36

    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.

    0 讨论(0)
提交回复
热议问题