对isa、IMP、SEL理解

560 阅读1分钟

ISA

@interface Object
{
	Class isa;	/* A pointer to the instance's class structure */
}

每一个类都会有isa指针,该指针指向类的结构体,如在底层objc_msgSent() 就是通过isa来查找该类的。再通过该类的super class查找父类等

#SEL 只是代表了选择器(方法名) 并不是方法的实现。 每一类都有一个调度表(dispatch table) 该表存储SEL 和Imp SEL相当于方法的名 并没有实现 当调用函数是可以根据sel 找到Imp imp则为指向函数实现 SEL的获取与使用

//第一种获取方法
SEL ABC =  @selector(aaa:);
//第二种获取方法(建议使用这个)
SEL ABC1 = NSSelectorFromString(@"aaa:");
[self performSelector:ABC];

#IMP 函数现实指针

#if !OBJC_OLD_DISPATCH_PROTOTYPES
typedef void (*IMP)(void /* id, SEL, ... */ ); 
#else
typedef id (*IMP)(id, SEL, ...); 
#endif
我们可以自己构建IMP指针
/**
 动态添加方法(这个是定义了一个函数实现指针IMP)

 @param self 接收者
 @param _cmd 选择器
 @param value 参数
 */
void dynamicMethod(id self, SEL _cmd, id value) {

    NSLog(@"首先尝试动态添加方法");
}
IMP  imp = (IMP)dynamicMethod;

//也可以通过选择器获取其IMP
IMP methodPoint = [self methodForSelector:methodId];

//通过runtime获取IMP
IMP imp = class_getMethodImplementation([self class], @selector(abc:));