Objective-C: Get list of subclasses from superclass

后端 未结 2 1742
悲&欢浪女
悲&欢浪女 2021-01-04 11:54

In Objective-C is there a way to ask a Class if there are any Subclass implementations.

I have a Base class which has multiple subclasses. I would like to loop throu

相关标签:
2条回答
  • 2021-01-04 12:23

    You can never list subclasses of a class. In (almost) any programming language. This is one of the basic properties of Object Oriented Programming.

    Consider changing your object model.

    What you probably want is to create an abstract class and different subclasses but you shouldn't access the subclasses from the abstract class. You should create another object (Factory class) which registers the subclasses and selects the appropiate one when needed.

    Note that you cannot efficiently register a class from the class itself. For a class code to be executed, the class has to be loaded first. That means, you have to import its header in some other class and that means that you are actually registering the class by importing its header. There are two possible solutions:

    1. Your factory class has to know the names of all subclasses (either at compile time or reading some configuration file).
    2. Your factory class has a method to which anyone can pass the name of a class to be registered. This is the right solution if you want external libraries to register a new subclass. Then you can put the subclass registration code into the main header of the library.
    0 讨论(0)
  • 2021-01-04 12:36

    This function gives you all subclasses of a class:

    #import <objc/runtime.h>
    
    NSArray *ClassGetSubclasses(Class parentClass)
    {
      int numClasses = objc_getClassList(NULL, 0);
      Class *classes = NULL;
    
      classes = (__unsafe_unretained Class *)malloc(sizeof(Class) * numClasses);
      numClasses = objc_getClassList(classes, numClasses);
    
      NSMutableArray *result = [NSMutableArray array];
      for (NSInteger i = 0; i < numClasses; i++)
      {
        Class superClass = classes[i];
        do
        {
          superClass = class_getSuperclass(superClass);
        } while(superClass && superClass != parentClass);
    
        if (superClass == nil)
        {
          continue;
        }
    
        [result addObject:classes[i]];
      }
    
      free(classes);
    
      return result;
    }
    

    Taken from Cocoa with Love.

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