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

断了今生、忘了曾经 提交于 2019-12-03 06:38:50

问题


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?


回答1:


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);
}



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/6396298/finding-classes-that-declare-that-they-conform-to-a-specific-protocol-using-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!