iOS开发runtime总结
runtime 运行时-最重要的机制是消息机制
消息机制的本质:任何方法的调用都是发送消息
SEL:方法编号,根据方法编号可以找到对用的方法。
运行时就是发送消息,当想使用系统的一些方法时候需要用到运行时去掉用。xcode5之后苹果不推荐使用底层方法,在xcode5之后使用运行时-build set 搜索msg 将yes改为no。
消息机制:让p(Person的实例对象)发送一个消息
objc_msgSend(p,@seletor(eat));
objc_msgSend(p,@seletor(run:),10); 10 是方法带的参数。
调用类方法的本质:将类名转换为类对象,由类对象调用
[Person eat]; -> Class personClass = [Person class];
[personClass performSelector:@selector(eat)];
运行时:objc_msgSend(personClass,@selector(eat));
使用runtime交换方法
使用场景:系统自带的方法功能不够,给系统的方法扩展一些功能,并保持原有功能。
1、继承系统的类,重写方法添加。
2、使用runtime交换方法。
class_getInstanceMethod-获取对象方法
class_getClassMethod - 获取类方法
class_getClassMethodImplentation - 获取类方法的实现
//获取imageName Class获取哪个类的方法 SEL获取方法编号 根据sel获去对应的class找方法
Method imageNameMethod = class_getClassMethod([UIImage class], @selector(imageNamed:));
Method xmg_imageNameMethod = class_getClassMethod([UIImage class], @selector(xmg_imageNamed:));
//交换方法的实现
method_exchangeImplementations(imageNameMethod, xmg_imageNameMethod);
IMP:方法实现
分类中不能用super ,分类没有super。
runtime动态添加方法
void eat2(id self,SEL _cmd,id param1){
NSLog(@"调用了eat %@ %@ %@",self,NSStringFromSelector(_cmd),param1);
}
默认一个方法都有两个参数 self(方法调用者),_cmd(调用方法的编号)一般叫做隐式参数。
动态添加方法,首先实现resolveInstanceMethod(对象方法)。
//resolveInstanceMethod-调用:当一个方法没用实现的,但是又被调用的时候,就会调用。
//resolveInstanceMethod-作用:知道哪些方法没用实现从而动态添加方法。
runtime动态添加属性
@property在分类中只会生成get方法不会生成set方法实现