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?
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.
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.
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);
}
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()).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With