drekka
drekka

Reputation: 21883

Finding classes that declare that they conform to a specific protocol using the Objective-C runtime

I'm trying to figure out a way to "tag" classes which will be written later so I can find them at runtime, but without enforcing the usage of a specific parent classes. Currently I'm looking at perhaps applying a protocol and then finding all classes which have that protocol.

But I've not be able to figure out how.

Does anyone know if it's possible to find all classes which implement a specific protocol at runtime? or alternatively - is there a better way to "tag" classes and find them?

Upvotes: 18

Views: 2895

Answers (3)

drekka
drekka

Reputation: 21883

Just in case anyone is interested in this old question, I eventually wrote some code the located all the bundles for the application and scanned the classes in those bundles. This was far more efficient than using code based on objc_getClassList because it scanned a limited number of classes as opposed to the entire runtime.

If you are interested you can find the code I was using here: https://github.com/drekka/Alchemic/blob/master/alchemic/NSBundle%2BAlchemic.m

Upvotes: 1

Caleb
Caleb

Reputation: 124997

I think you'll have to iterate over the list of classes (objc_getClassList()) and check whether each implements the protocol in question (class_conformsToProtocol()).

Upvotes: 1

aroth
aroth

Reputation: 54806

It doesn't look like this should be too difficult using the Objective-C Runtime API. Specifically, it looks like you can use objc_getClassList and class_conformsToProtocol to do something like:

Class* classes = NULL;
int numClasses = objc_getClassList(NULL, 0);
if (numClasses > 0 ) {
    classes = malloc(sizeof(Class) * numClasses);
    numClasses = objc_getClassList(classes, numClasses);
    for (int index = 0; index < numClasses; index++) {
        Class nextClass = classes[index];
        if (class_conformsToProtocol(nextClass, @protocol(MyTaggingProtocol))) {
            //found a tagged class, add it to the result-set, etc.
        }
    }
    free(classes);
}

Upvotes: 28

Related Questions