一、runtime简介
1.runtime 简称运行时,OC就是运行时机制,也就是在运行时候的一些机制,其中最主要的是消息机制
2.对于C语言,函数在编译的时候会决定调用哪个函数
3.对于OC函数,属于动态调用过程,在编译的时候并不能决定真正调用哪个函数,只有在真正运行的时候才会根据函数的名称找到对应的函数
实践证明:在编译阶段,OC可以调用任何函数,即使这个函数并未实现,只要声明过就不会报错
在编译阶段,C语言调用未实现的函数就会报错
二、runtime的作用
1.发送消息
~方法调用的本质,就是让对象发送消息
~objc_msgSend只有对象才能发送消息,因此以objc开头
2.使用运行时消息机制的步骤:
~先导入 #import<objc/message.h>
四、runtime动态添加方法
添加不带参数的方法:
@implementation Person
//动态添加方法,首先实现这个resolveInstanceMethod
//resolveInstanceMethod调用时间:调用了一个没有实现的方法,这时会调用resolveInstanceMethod方法
//resolveInstanceMethod方法作用:
//sel:为没有实现的方法
void addrun()
{
NSLog(@"动态添加了一个方法");
}
+(BOOL)resolveInstanceMethod:(SEL)sel
{
if (sel==@selector(run)) {
/*
cls:给哪个类添加方法
SEL:添加方法的方法编号是什么
IMP:方法实现,函数入口,函数名
types:方法类型
*/
class_addMethod(self, sel, (IMP)addrun, "v@:");
return YES;
}
return [super resolveInstanceMethod:sel];
}
@end
Person * person = [[Person alloc]init];
[person performSelector:@selector(run) withObject:nil];
添加一个带参数的方法
@implementation Person
//动态添加方法,首先实现这个resolveInstanceMethod
//resolveInstanceMethod调用时间:调用了一个没有实现的方法,这时会调用resolveInstanceMethod方法
//resolveInstanceMethod方法作用:
//sel:为没有实现的方法
void addrun(id self,SEL _cmd,id param)
{
NSLog(@"动态添加了一个方法---------%@",param);
}
+(BOOL)resolveInstanceMethod:(SEL)sel
{
if (sel==@selector(run)) {
/*
cls:给哪个类添加方法
SEL:添加方法的方法编号是什么
IMP:方法实现,函数入口,函数名
types:方法类型
*/
class_addMethod(self, sel, (IMP)addrun, "v@:@");
return YES;
}
return [super resolveInstanceMethod:sel];
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person * person = [[Person alloc]init];
[person performSelector:@selector(run) withObject:@123];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
class_addMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>, <#IMP imp#>, <#const char *types#>)
传递的各个参数说明
cls:给哪个类添加方法
SEL:添加方法的方法编号是什么
IMP:方法实现,函数入口,函数名
types:方法类型 方法类型确定需要到
五、动态添加属性