Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 627
drekka Avatar asked Jun 18 '11 13:06

drekka


People also ask

How do you conform to a protocol in Objective-C?

Objective-C Language Protocols Conforming to Protocols It is also possible for a class to conform to multiple protocols, by separating them with comma. Like when conforming to a single protocol, the class must implement each required method of each protocols, and each optional method you choose to implement.

What is the Objective-C runtime?

The Objective-C runtime is a runtime library that provides support for the dynamic properties of the Objective-C language, and as such is linked to by all Objective-C apps. Objective-C runtime library support functions are implemented in the shared library found at /usr/lib/libobjc.


2 Answers

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);
}
like image 95
aroth Avatar answered Nov 11 '22 07:11

aroth


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()).

like image 42
Caleb Avatar answered Nov 11 '22 06:11

Caleb