Fuck iOS EveryDay

methodSignatureForSelector方法

2017-04-28  本文已影响72人  SpursGo

转自土土哥的博客,mark一下,方便以后查阅

只记录结论 分析过程略过
1.对于类,只要@implementation里实现了方法,不管@interface是否有声明,都可以返回methodSignature
2.对于Protocol声明的方法,不管实例方法还是类方法,不管required还是optional的,都可以返回methodSignature

image.png
// 模拟实现___methodDescriptionForSelector方法:
struct objc_method_description ttg_MethodDescription(Class class, SEL sel) {
    // 结果
    struct objc_method_description description = (struct objc_method_description){NULL, NULL};
    Class currentClass = class;
    
    while (currentClass && description.name == NULL) {
        // 获取Protocol列表
        unsigned int count = 0;
        __unsafe_unretained Protocol **protocols = class_copyProtocolList(currentClass, &count);
        
        // 遍历所有Protocol
        for (unsigned int i = 0; i < count; i++) {
            // Required 方法
            description = protocol_getMethodDescription(protocols[i], sel, YES, class_isMetaClass(currentClass) ^ 1);
            if (description.name != NULL) {
                break;
            }
            
            // Optional 方法
            description = protocol_getMethodDescription(protocols[i], sel, NO, class_isMetaClass(currentClass) ^ 1);
            if (description.name != NULL) {
                break;
            }
        }
        
        // 释放
        free(protocols);
        
        // 找到、返回
        if (description.name != NULL) {
            return description;
        }
        
        // 获取父类,继续
        currentClass = class_getSuperclass(currentClass);
    }
    
    // 获取实例方法
    Method method = class_getInstanceMethod(class, sel);
    if (method) {
        // 找到实例方法
        return *method_getDescription(method);
    } else {
        // 返回空
        return (struct objc_method_description){NULL, NULL};
    }
}

上一篇下一篇

猜你喜欢

热点阅读