methodSignatureForSelector方法

转自土土哥的博客,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};
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 5,879评论 0 9
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,073评论 19 139
  • 1、随机数 不需要随机数种子 arc4random()%N + begin:产生begin~begin+N的随机数...
    我是小胡胡123阅读 9,767评论 0 2
  • 132.转换错误成可选值 通过转换错误成一个可选值,你可以使用 try? 来处理错误。当执行try?表达式时,如果...
    无沣阅读 5,132评论 0 3
  • Mr.liu估计正在火车上打盹儿,我在等着我的罪恶的晚饭,因为最近几天已经告别s号的衣服了,而我虽然在心里默默的发...
    一本小情书阅读 1,891评论 1 1

友情链接更多精彩内容