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
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:
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.