一、定义
OC是动态语言,所以许多代码是在编译以后执行的,也就是运行时执行,在运行时OC代码会转变成runtime的C语言代码来执行,这就是运行时系统。
1、关于OC是动态语言的解释:
1)、动态类型:在运行时才能决定数据的类型,即id类型,静态类型在编译过程中如果不对应就会检测出报错,而id类型只有在运行时才能识别。
2)、动态方法:一般来说如果某一个类型确定了,那么与其对应的方法也确定了,但是我们可以在消息发送时在 resolveInstanceMethod:里通过 class_addMethod 动态添加方法,如有未实现的方法,即可通过该方法实现imp
3)、动态加载:对于不同分辨率的机型可以动态添加@2x,@3x 的图片
2、底层实现原理
对于一句普通的代码:
Person * p = [[Person alloc]init];
[p eat:@"饭"];
翻译成runtime语言为:
Person * p = objc_msgSend(objc_getClass("Person"), sel_registerName("alloc"));
p = objc_msgSend(p, sel_registerName("init"));
objc_msgSend(p, sel_registerName("eat:"),@"饭");
其中用到了几个常用方法:
objc_msgSend - 发送消息
objc_getClass - 对应类名
sel_registerName - 对应方法sel
如果方法需要传参,可在后面直接添加。
二、配置
1、因为xcode不推荐使用底层语言,所以在使用runtime时需要配置一下:target->info搜索msg将YES改成NO,即可。
2、添加对应头文件
#import <objc/message.h>
#import <objc/runtime.h>
三、应用
1、方法欺骗
1) 首先需要将方法替换放到程序预加载中,以便程序中所使用到的地方都能用新方法实现。
+ (void)load{
}
程序先预加载 load方法,在进入main里面。
2) oc中有一张表对应方法,其中sel(编号) - imp(实现)(指针),因此如果想让两个方法实现对调但方法名字不对调,只要编号对应另一个实现指针就可以。
Method m1 = class_getClassMethod(self, @selector(URLWithString:));
Method m2 = class_getClassMethod(self, @selector(myUrlWithString:));
method_exchangeImplementations(m1, m2);
通过 method_exchangeImplementations 实现两个方法实现的对调,不过需要注意的是,新方法在实现的时候如果用到了旧方法,那么旧方法sel已经变成了新方法的imp,所以需要用新方法sel来对应旧方法的imp,如下:
+(instancetype)myUrlWithString:(NSString *)url
{
NSURL * URL = [NSURL myUrlWithString:url];
if (URL == nil) {
NSLog(@"空的");
}
return URL;
}
这里可以看到在 myUrlWithString 中依旧引用了 myUrlWithString,因为此时引用的 myUrlWithString 方法sel 已经对应了 URLWithString 的 实现imp。
2、遍历属性
在归档时通过遍历属性完成所有属性的归档
-(void)encodeWithCoder:(NSCoder *)aCoder
{
// 属性个数
unsigned int count = 0;
// 属性列表
Ivar * list = class_copyIvarList(self.class, &count);
for (int i=0; i<count; i++) {
Ivar ivar = list[i];
const char * name = ivar_getName(ivar);
NSString * key = [NSString stringWithUTF8String:name];
id value = [self valueForKey:key];
[aCoder encodeObject:value forKey:key];
}
// 手动释放
free(list);
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self == [super init]) {
unsigned int count = 0;
Ivar * list = class_copyIvarList(self.class, &count);
for (int i=0; i<count; i++) {
Ivar ivar = list[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
id value = [aDecoder decodeObjectForKey:key];
[self setValue:value forKey:key];
}
free(list);
}
return self;
}
ivar:成员变量
通过 class_copyIvarList 获取到类的所有属性和个数,在通过遍历来对每一个属性实现归档。