一、runtime简介
- RunTime简称运行时。OC就是
运行时机制
,也就是在运行时候的一些机制,其中最主要的是消息机制。 - 对于C语言,
函数的调用在编译的时候会决定调用哪个函数
。 - 对于OC的函数,属于
动态调用过程
,在编译的时候并不能决定真正调用哪个函数,只有在真正运行的时候才会根据函数的名称找到对应的函数来调用。 - 事实证明:
- 在编译阶段,OC可以
调用任何函数
,即使这个函数并未实现,只要声明过就不会报错。 - 在编译阶段,C语言调用
未实现的函数
就会报错。
- 在编译阶段,OC可以
二、常见方法:
使用运行时前提,必须导入#import <objc/runtime.h>
//获取某个类的类方法
Method class_getClassMethod(Class cls,SEL name);
//获取某个类的实例对象方法
Method class_getInstanceMethod(Class cls, SEL name);
//交换两个方法的实现
void method_exchangeImplementations(Method m1, Method m2);
unsigned int count = 0;
// 返回值是存放所有获取到的属性 哪一个类 放一个接受值得地址用来存放属性的个数
Ivar *ivars = class_copyIvarList([类 class], &count);
- 属性列表
objc_property_t *propertyList = class_copyPropertyList([self class], &count);
for (unsigned int i=0; i<count; i++) {
const char *propertyName = property_getName(propertyList[i]);
NSLog(@"property---->%@", [NSString stringWithUTF8String:propertyName]);
}
- 获取方法列表
Method *methodList = class_copyMethodList([self class], &count);
for (unsigned int i; i<count; i++) {
Method method = methodList[i];
NSLog(@"method---->%@", NSStringFromSelector(method_getName(method)));
}
- 获取成员变量列表(包括私有)
// 返回值是存放所有获取到的属性 哪一个类 放一个接受值得地址用来存放属性的个数
Ivar *ivarList = class_copyIvarList([self class], &count);
for (unsigned int i; i<count; i++) {
Ivar myIvar = ivarList[i];
const char *ivarName = ivar_getName(myIvar);
NSLog(@"Ivar---->%@", [NSString stringWithUTF8String:ivarName]);
}
- 获取协议列表
__unsafe_unretained Protocol **protocolList = class_copyProtocolList([self class], &count);
for (unsigned int i; i<count; i++) {
Protocol *myProtocal = protocolList[i];
const char *protocolName = protocol_getName(myProtocal);
NSLog(@"protocol---->%@", [NSString stringWithUTF8String:protocolName]);
}
- 获取某个类的类方法
Class PersonClass = object_getClass([Person class]);
SEL oriSEL = @selector(test1);
Method oriMethod = class_getInstanceMethod(xiaomingClass, oriSEL);
- 获取某个类的实例对象方法
Class PersonClass = object_getClass([xiaoming class]);
SEL oriSEL = @selector(test2);
Method cusMethod = class_getInstanceMethod(xiaomingClass, oriSEL);
- 添加方法
BOOL addSucc = class_addMethod(xiaomingClass, oriSEL, method_getImplementation(cusMethod), method_getTypeEncoding(cusMethod));
- 替换原方法实现
class_replaceMethod(toolClass, cusSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
- 交换两个方法的实现 (方法交换应该被保证,在程序中只会执行一次)
void method_exchangeImplementations(Method m1 , Method m2)
三、runtime作用
发送消息
方法调用的本质
,就是让对象发送消息。- objc_msgSend,只有对象才能发送消息,因此以objc开头.
- 使用
消息机制
前提,必须导入#import <objc/message.h> - 消息机制简单使用
// 创建person对象
Person *p = [[Person alloc] init];
// 调用对象方法
[p eat];
// 本质:让对象发送消息
objc_msgSend(p, @selector(eat));
// 调用类方法的方式:两种
// 第一种通过类名调用
[Person eat];
// 第二种通过类对象调用
[[Person class] eat];
// 用类名调用类方法,底层会自动把类名转换成类对象调用
// 本质:让类对象发送消息
objc_msgSend([Person class], @selector(eat));
- 消息机制原理:对象根据方法编号SEL去映射表查找对应的方法实现
2、交换两个方法的实现
需要导入头文件 <objc/runtime.h>
- 创建一个Person类,类中实现以下两个类方法,并在.h 文件中声明
+ (void)run {
NSLog(@"跑");
}
+ (void)study {
NSLog(@"学习");
}
控制器中调用,则先打印跑,后打印学习
[Person run];
[Person study];
下面是通过runtime实现方法交换,类方法用class_getClassMethod,对象方法用class_getInstanceMethod
(方法交换应该被保证,在程序中只会执行一次)
// 获取两个类的类方法
Method m1 = class_getClassMethod([Person class], @selector(run));
Method m2 = class_getClassMethod([Person class], @selector(study));
// 开始交换方法实现
method_exchangeImplementations(m1, m2);
// 交换后,先打印学习,再打印跑!
[Person run];
[Person study];
3、拦截系统自带的方法调用功能
比如不同系统显示图片不一样的效果,需要在客户端进行处理,如何处理呢?
1、为UIImage建一个分类(UIImage+Category)
2、在分类中实现一个自定义方法,方法中写要在系统方法中加入的语句,比如版本判断
+ (UIImage *)xh_imageNamed:(NSString *)name {
double version = [[UIDevice currentDevice].systemVersion doubleValue];
if (version >= 7.0) {
// 如果系统版本是7.0以上,使用另外一套文件名结尾是‘_os7’的扁平化图片
name = [name stringByAppendingString:@"_os7"];
}
NSLog(@"%@",name);
return [UIImage xh_imageNamed:name];
}
3、在分类中重写UIImage的load方法,实现方法的交换(只要能让其执行一次方法交换语句,load在合适不过了)
+ (void)load {
// 获取两个类的类方法
Method m1 = class_getClassMethod([UIImage class], @selector(imageNamed:));
Method m2 = class_getClassMethod([UIImage class], @selector(xh_imageNamed:));
// 开始交换方法实现
method_exchangeImplementations(m1, m2);
}
注意:自定义方法中最后一定要在调用一下系统的方法,让其有加载图片的功能,但是由于方法交换,系统的方法名已经变成了自定义的方法名(有点绕,就是用我们的方法能调用系统的方法,用系统的名字能调用我们的方法),这就实现了系统方法的拦截
交换原理:
交换之前:
交换之后:
4、动态添加方法
开发使用场景
:如果一个类方法非常多,加载类到内存的时候也比较耗费资源,需要给每个方法生成映射表,可以使用动态给某个类,添加方法解决。经典面试题
:有没有使用performSelector,其实主要想问你有没有动态添加过方法。简单使用
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Person *p = [[Person alloc] init];
// 默认person,没有实现eat方法,可以通过performSelector调用,但是会报错。
// 动态添加方法就不会报错
[p performSelector:@selector(eat)];
}
@end
@implementation Person
// void(*)()
// 默认方法都有两个隐式参数,
void eat(id self,SEL sel)
{
NSLog(@"%@ %@",self,NSStringFromSelector(sel));
}
// 当一个对象调用未实现的方法,会调用这个方法处理,并且会把对应的方法列表传过来.
// 刚好可以用来判断,未实现的方法是不是我们想要动态添加的方法
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
if (sel == @selector(eat)) {
// 动态添加eat方法
// 第一个参数:给哪个类添加方法
// 第二个参数:添加方法的方法编号
// 第三个参数:添加方法的函数实现(函数地址)
// 第四个参数:函数的类型,(返回值+参数类型) v:void @:对象->self :表示SEL->_cmd
class_addMethod(self, @selector(eat), eat, "v@:");
}
return [super resolveInstanceMethod:sel];
}
@end
5、给分类添加属性
原理:给一个类声明属性,其实本质就是给这个类添加关联,并不是直接把这个值得内存空间添加到内存空间。
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 给系统NSObject类动态添加属性name
NSObject *objc = [[NSObject alloc] init];
objc.name = @"this is name";
NSLog(@"%@",objc.name);
}
@end
// 定义关联的key
static const char *key = "name";
@implementation NSObject (Property)
- (NSString *)name
{
// 根据关联的key,获取关联的值。
return objc_getAssociatedObject(self, key);
}
- (void)setName:(NSString *)name
{
// 第一个参数:给哪个对象添加关联
// 第二个参数:关联的key,通过这个key获取
// 第三个参数:关联的value
// 第四个参数:关联的策略
objc_setAssociatedObject(self, key, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
6、字典转模型
KVC字典转模型弊端:必须保证,模型中的属性和字典中的key一一对应。
1、如果不一致,就会调用[<Status 0x7fa74b545d60> setValue:forUndefinedKey:]报key找不到的错
2、分析:模型中的属性和字典的key不一一对应,系统就会调用setValue:forUndefinedKey: 报错。
3、解决:重写对象的setValue:forUndefinedKey: 把系统的方法覆盖,就能继续使用KVC,字典转模型了。
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
}
Runtime字典转模型方式:
思路:利用运行时,遍历模型中所有属性,根据模型的属性名,去字典中查找key,取出对应的值,给模型的属性赋值
步骤:提供一个NSObject分类,专门字典转模型,以后所有模块都可以通过这个分类转。
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 解析Plist文件
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"status.plist" ofType:nil];
NSDictionary *statusDict = [NSDictionary dictionaryWithContentsOfFile:filePath];
// 获取字典数组
NSArray *dictArr = statusDict[@"statuses"];
// 自动生成模型的属性字符串
// [NSObject resolveDict:dictArr[0][@"user"]];
_statuses = [NSMutableArray array];
// 遍历字典数组
for (NSDictionary *dict in dictArr) {
Status *status = [Status modelWithDict:dict];
[_statuses addObject:status];
}
// 测试数据
NSLog(@"%@ %@",_statuses,[_statuses[0] user]);
}
@end
@implementation NSObject (Model)
+ (instancetype)modelWithDict:(NSDictionary *)dict
{
// 思路:遍历模型中所有属性-》使用运行时
// 0.创建对应的对象
id objc = [[self alloc] init];
// 1.利用runtime给对象中的成员属性赋值
// class_copyIvarList:获取类中的所有成员属性
// Ivar:成员属性的意思
// 第一个参数:表示获取哪个类中的成员属性
// 第二个参数:表示这个类有多少成员属性,传入一个Int变量地址,会自动给这个变量赋值
// 返回值Ivar *:指的是一个ivar数组,会把所有成员属性放在一个数组中,通过返回的数组就能全部获取到。
/* 类似下面这种写法
Ivar ivar;
Ivar ivar1;
Ivar ivar2;
// 定义一个ivar的数组a
Ivar a[] = {ivar,ivar1,ivar2};
// 用一个Ivar *指针指向数组第一个元素
Ivar *ivarList = a;
// 根据指针访问数组第一个元素
ivarList[0];
*/
unsigned int count;
// 获取类中的所有成员属性
Ivar *ivarList = class_copyIvarList(self, &count);
for (int i = 0; i < count; i++) {
// 根据角标,从数组取出对应的成员属性
Ivar ivar = ivarList[i];
// 获取成员属性名
NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
// 处理成员属性名->字典中的key
// 从第一个角标开始截取
NSString *key = [name substringFromIndex:1];
// 根据成员属性名去字典中查找对应的value
id value = dict[key];
// 二级转换:如果字典中还有字典,也需要把对应的字典转换成模型
// 判断下value是否是字典
if ([value isKindOfClass:[NSDictionary class]]) {
// 字典转模型
// 获取模型的类对象,调用modelWithDict
// 模型的类名已知,就是成员属性的类型
// 获取成员属性类型
NSString *type = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
// 生成的是这种@"@\"User\"" 类型 -》 @"User" 在OC字符串中 \" -> ",\是转义的意思,不占用字符
// 裁剪类型字符串
NSRange range = [type rangeOfString:@"\""];
type = [type substringFromIndex:range.location + range.length];
range = [type rangeOfString:@"\""];
// 裁剪到哪个角标,不包括当前角标
type = [type substringToIndex:range.location];
// 根据字符串类名生成类对象
Class modelClass = NSClassFromString(type);
if (modelClass) { // 有对应的模型才需要转
// 把字典转模型
value = [modelClass modelWithDict:value];
}
}
// 三级转换:NSArray中也是字典,把数组中的字典转换成模型.
// 判断值是否是数组
if ([value isKindOfClass:[NSArray class]]) {
// 判断对应类有没有实现字典数组转模型数组的协议
if ([self respondsToSelector:@selector(arrayContainModelClass)]) {
// 转换成id类型,就能调用任何对象的方法
id idSelf = self;
// 获取数组中字典对应的模型
NSString *type = [idSelf arrayContainModelClass][key];
// 生成模型
Class classModel = NSClassFromString(type);
NSMutableArray *arrM = [NSMutableArray array];
// 遍历字典数组,生成模型数组
for (NSDictionary *dict in value) {
// 字典转模型
id model = [classModel modelWithDict:dict];
[arrM addObject:model];
}
// 把模型数组赋值给value
value = arrM;
}
}
if (value) { // 有值,才需要给模型的属性赋值
// 利用KVC给模型中的属性赋值
[objc setValue:value forKey:key];
}
}
return objc;
}
@end
7、动态变量控制
在程序中,对象的age是10,后来被runtime变成了20,来看看runtime是怎么做到的。
1、动态获取对象类中的所有属性 [包括私有]
Ivar *ivar = class_copyIvarList([Person class], &count)
2、遍历属性找到对应name 字段
const char *varName = ivar_getName(var)
3、修改对应的字段值成20
object_setIvar(p,var,@"20")
4、代码
unsigned int count = 0;
Person *p = [[Person alloc] init];
Ivar *ivar = class_copyIvarList([p class], &count);
for (int i = 0; i<count; i++) {
Ivar var = ivar[i];
const char *varName = ivar_getName(var);
NSString *name = [NSString stringWithUTF8String:varName];
if ([name isEqualToString:@"_age"]) {
object_setIvar(p, var, @"20");
break;
}
}
NSLog(@"对象 age is %@",对象.age);
这里是关于Runtime 的相关资料
runtime 文章专题 (http://www.jianshu.com/collection/dc947eab6af3) (13+关于runtime的)
文1 OC最实用的runtime总结,面试、工作你看我就足够了! (http://www.jianshu.com/p/ab966e8a82e2)
袁峥 让你快速上手Runtime (http://www.jianshu.com/p/e071206103a4)