- 类对象中有类方法和实例方法的列表,列表中记录着方法的名词、参数和实现,而 selector 本质就是方法名称,runtime 通过这个方法名称就可以在列表中找到该方法对应的实现。
- 如下所示,objc_class 的底层定义声明了一个指向 struct objc_method_list 指针的指针,可以包含类方法列表和实例方法列表:
struct objc_class {
Class _Nonnull isa OBJC_ISA_AVAILABILITY;
#if !__OBJC2__
Class _Nullable super_class OBJC2_UNAVAILABLE;
const char * _Nonnull name OBJC2_UNAVAILABLE;
long version OBJC2_UNAVAILABLE;
long info OBJC2_UNAVAILABLE;
long instance_size OBJC2_UNAVAILABLE;
struct objc_ivar_list * _Nullable ivars OBJC2_UNAVAILABLE;
struct objc_method_list * _Nullable * _Nullable methodLists OBJC2_UNAVAILABLE;
struct objc_cache * _Nonnull cache OBJC2_UNAVAILABLE;
struct objc_protocol_list * _Nullable protocols OBJC2_UNAVAILABLE;
#endif
} OBJC2_UNAVAILABLE;
- 在寻找 IMP 的地址时,runtime 提供两种方法:
IMP class_getMethodImplementation(Class cls, SEL name);
IMP method_getImplementation(Method m);
- 对于 class_getMethodImplementation 方法而言,类方法和实例方法实际上都是通过调用 class_getMethodImplementation() 来寻找 IMP 地址:
- (void)getIMP_class_getMethodImplementationFromSelector:(SEL)aSelector {
const char *className = object_getClassName([self class]);
IMP instanceIMP = class_getMethodImplementation(objc_getClass(className), aSelector);
IMP classIMP = class_getMethodImplementation(objc_getMetaClass(className), aSelector);
NSLog(@"instanceIMP:%p classIMP:%p", instanceIMP, classIMP);
}
- 对 method_getImplementation 而言,传入的参数只有 method:
- (void)getIMP_method_getImplementationFromSelector:(SEL)aSelector {
const char *className = object_getClassName([self class]);
Method instanceMethod = class_getInstanceMethod(objc_getClass(className), aSelector);
Method classMethod = class_getClassMethod(objc_getClass(className), aSelector);
IMP instanceIMP = method_getImplementation(instanceMethod);
IMP classIMP = method_getImplementation(classMethod);
NSLog(@"instanceIMP:%p classIMP:%p", instanceIMP, classIMP);
}
- 区分类方法和实例方法在于封装 method 的函数:
Method class_getClassMethod(Class cls, SEL name)
Method class_getInstanceMethod(Class cls, SEL name)
- 最后调用 IMP method_getImplementation(Method m) 获取 IMP 地址。
- 方法列表中保存着下面方法的结构体,结构体中包含这方法的实现,selector 本质就是方法的名称,通过该方法名称,即可在结构体中找到相应的实现:
struct objc_method {
SEL method_name
char *method_types
IMP method_imp
}