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

时间秒杀一切 提交于 2019-12-02 19:11:32

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

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

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