概述
类对象中有类方法和实例方法的列表,列表中记录着方法的名词、参数和实现,而 selector 本质就是方法名称,runtime 通过这个方法名称就可以在列表中找到该方法对应的实现。这里声明了一个指向 struct objc_method_list 指针的指针,可以包含类方法列表和实例方法列表。
具体实现
在寻找 IMP 的地址时,runtime提供了两种方法IMP class_getMethodImplementation(Class cls, SEL name);IMP method_getImplementation(Method m)
而根据官方描述,第一种方法可能会更快一些
@note \c class_getMethodImplementation may be faster than \c method_getImplementation(class_getInstanceMethod(cls, name)).
对于第一种方法而言,类方法和实例方法实际上都是通过调用class_getMethodImplementation()来寻找IMP地址的,不同之处在于传入的第一个参数不同
类方法(假设有一个类A)class_getMethodImplementation(objc_getMetaClass("A"),@selector(methodName));
实例方法class_getMethodImplementation([A class],@selector(methodName));
通过该传入的参数不同,找到不同的方法列表,方法列表中保存着下面方法的结构体,结构体中包含这方法的实现,selector本质就是方法的名称,通过该方法名称,即可在结构体中找到相应的实现。struct objc_method {SEL method_namechar *method_typesIMP method_imp}
而对于第二种方法而言,传入的参数只有method,区分类方法和实例方法在于封装method的函数
类方法
Method class_getClassMethod(Class cls, SEL name)
实例方法
Method class_getInstanceMethod(Class cls, SEL name)
最后调用IMP method_getImplementation(Method m)获取IMP地址
网友评论