当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOS runtime知识梳理

iOS runtime知识梳理

2019年07月24日  | 移动技术网移动技术  | 我要评论
一、runtime简介 runtime简称运行时。oc就是运行时机制,也就是在运行时候的一些机制,其中最主要的是消息机制。 对于c语言,函数的调用在编译的时候会决定调用

一、runtime简介

runtime简称运行时。oc就是运行时机制,也就是在运行时候的一些机制,其中最主要的是消息机制。

对于c语言,函数的调用在编译的时候会决定调用哪个函数

对于oc的函数,属于动态调用过程,在编译的时候并不能决定真正调用哪个函数,只有在真正运行的时候才会根据函数的名称找到对应的函数来调用。

事实证明:

  • 在编译阶段,oc可以调用任何函数,即使这个函数并未实现,只要声明过就不会报错。
  • 在编译阶段,c语言调用未实现的函数就会报错。

二、runtime作用

1.发送消息

▪ 方法调用的本质,就是让对象发送消息。

▪ objc_msgsend,只有对象才能发送消息,因此以objc开头.

▪ 使用消息机制前提,必须导入#import <objc/message.h>

▪ 消息机制简单使用

▪ clang -rewrite-objc main.m 查看最终生成代码

 // 创建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.交换方法

▪ 开发使用场景:系统自带的方法功能不够,给系统自带的方法扩展一些功能,并且保持原有的功能。

▪ 方式一:继承系统的类,重写方法.

▪ 方式二:使用runtime,交换方法.

@implementation viewcontroller
- (void)viewdidload {
 [super viewdidload];
 // do any additional setup after loading the view, typically from a nib.
 // 需求:给imagenamed方法提供功能,每次加载图片就判断下图片是否加载成功。
 // 步骤一:先搞个分类,定义一个能加载图片并且能打印的方法+ (instancetype)imagewithname:(nsstring *)name;
 // 步骤二:交换imagenamed和imagewithname的实现,就能调用imagewithname,间接调用imagewithname的实现。
 uiimage *image = [uiimage imagenamed:@"123"];
}
@end
@implementation uiimage (image)
// 加载分类到内存的时候调用
+ (void)load
{
 // 交换方法
 // 获取imagewithname方法地址
 method imagewithname = class_getclassmethod(self, @selector(imagewithname:));
 // 获取imagewithname方法地址
 method imagename = class_getclassmethod(self, @selector(imagenamed:));
 // 交换方法地址,相当于交换实现方式
 method_exchangeimplementations(imagewithname, imagename);
}
// 不能在分类中重写系统方法imagenamed,因为会把系统的功能给覆盖掉,而且分类中不能调用super.
// 既能加载图片又能打印
+ (instancetype)imagewithname:(nsstring *)name
{
 // 这里调用imagewithname,相当于调用imagename
 uiimage *image = [self imagewithname:name];
 if (image == nil) {
 nslog(@"加载空的图片");
 }
 return image;
}
@end

▪ 交换原理:

交换之前:

交换之后:

3.动态添加方法

▪ 开发使用场景:如果一个类方法非常多,加载类到内存的时候也比较耗费资源,需要给每个方法生成映射表,可以使用动态给某个类,添加方法解决。

▪ 经典面试题:有没有使用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

4.给分类添加属性

原理:给一个类声明属性,其实本质就是给这个类添加关联,并不是直接把这个值的内存空间添加到类存空间。

@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 = @"小码哥";
 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

5.字典转模型

设计模型:字典转模型的第一步

  • 模型属性,通常需要跟字典中的key一一对应
  • 问题:一个一个的生成模型属性,很慢?
  • 需求:能不能自动根据一个字典,生成对应的属性。
  • 解决:提供一个分类,专门根据字典生成对应的属性字符串。
@implementation nsobject (log)
// 自动打印属性字符串
+ (void)resolvedict:(nsdictionary *)dict{
 // 拼接属性字符串代码
 nsmutablestring *strm = [nsmutablestring string];
 // 1.遍历字典,把字典中的所有key取出来,生成对应的属性代码
 [dict enumeratekeysandobjectsusingblock:^(id _nonnull key, id _nonnull obj, bool * _nonnull stop) {
 // 类型经常变,抽出来
  nsstring *type;
 if ([obj iskindofclass:nsclassfromstring(@"__nscfstring")]) {
  type = @"nsstring";
 }else if ([obj iskindofclass:nsclassfromstring(@"__nscfarray")]){
  type = @"nsarray";
 }else if ([obj iskindofclass:nsclassfromstring(@"__nscfnumber")]){
  type = @"int";
 }else if ([obj iskindofclass:nsclassfromstring(@"__nscfdictionary")]){
  type = @"nsdictionary";
 }
 // 属性字符串
 nsstring *str;
 if ([type containsstring:@"ns"]) {
  str = [nsstring stringwithformat:@"@property (nonatomic, strong) %@ *%@;",type,key];
 }else{
  str = [nsstring stringwithformat:@"@property (nonatomic, assign) %@ %@;",type,key];
 }
 // 每生成属性字符串,就自动换行。
 [strm appendformat:@"\n%@\n",str];
 }];
 // 把拼接好的字符串打印出来,就好了。
 nslog(@"%@",strm);
}
@end

字典转模型的方式一:kvc

@implementation status
+ (instancetype)statuswithdict:(nsdictionary *)dict
{
 status *status = [[self alloc] init];
 [status setvaluesforkeyswithdictionary:dict];
 return status;
}
@end

kvc字典转模型弊端:必须保证,模型中的属性和字典中的key一一对应。

▪ 如果不一致,就会调用[<status 0x7fa74b545d60> setvalue:forundefinedkey:]  key找不到的错。

▪ 分析:模型中的属性和字典的key不一一对应,系统就会调用setvalue:forundefinedkey:报错

▪ 解决:重写对象的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

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网