iOS中runtime运行机制解析

转自http://blog.csdn.net/fuzheng0301/article/details/46898405

一.先思考两个问题:

第一个问题, 
1》runtime实现的机制是什么,怎么用,一般用于干嘛? 
这个问题我就不跟大家绕弯子了,直接告诉大家, 
runtime是一套比较底层的纯C语言API, 属于1个C语言库, 包含了很多底层的C语言API。 
在我们平时编写的OC代码中, 程序运行过程时, 其实最终都是转成了runtime的C语言代码, runtime算是OC的幕后工作者 
比如说,下面一个创建对象的方法中, 
举例: 
OC : 
[[MJPerson alloc] init] 
runtime : 
objc_msgSend(objc_msgSend(“MJPerson” , “alloc”), “init”)


第二个问题 
runtime 用来干什么呢??用在那些地方呢?怎么用呢? 
runtime是属于OC的底层, 可以进行一些非常底层的操作(用OC是无法现实的, 不好实现)

  • 在程序运行过程中, 动态创建一个类(比如KVO的底层实现)

  • 在程序运行过程中, 动态地为某个类添加属性\方法, 修改属性值\方法

  • 遍历一个类的所有成员变量(属性)\所有方法 
    例如:我们需要对一个类的属性进行归档解档的时候属性特别的多,这时候,我们就会写很多对应的代码,但是如果使用了runtime就可以动态设置!

二.学习runtime机制首先要了解下面几个问题 

       Objective-c是一门编译型、动态语言(这里强调下oc是静态类型语言),这在开发语言中是并多见的,一般的动态语言多为解释性语言。OC之所以能够做到即使编译型语言,又是动态语言。就是得益于RunTime机制。

1.相关的头文件和函数 
1> 头文件

  • 利用头文件,我们可以查看到runtime中的各个方法!

2> 相关应用

  • NSCoding(归档和解档, 利用runtime遍历模型对象的所有属性)
  • 字典 –> 模型 (利用runtime遍历模型对象的所有属性, 根据属性名从字典中取出对应的值, 设置到模型的属性上)
  • KVO(利用runtime动态产生一个类)
  • 用于封装框架(想怎么改就怎么改) 
    这就是我们runtime机制的只要运用方向

3> 相关函数

  • 1、class_copyPropertyList  获取一份拷贝的成员列表数组

    2、property_getName获取成员名称

    3、class_getInstanceVariable  获取成员对象的Ivar

    4、object_getIvar从Ivar对象中取值

    5、object_setIvar赋值函数

    6、objc_msgSend : 给对象发送消息

    7、class_copyMethodList : 遍历某个类所有的方法

    8、class_copyIvarList : 遍历某个类所有的成员变量

    9、class_…..

    这些是我们学习runtime必须知道的函数!

2.必备常识 
1> Ivar : 成员变量 
2> Method : 成员方法 
从上面例子中我们看到我们定义的成员变量,如果要是动态创建方法,可以使用Method,


三.我们通过一幅图可以看清楚OC中类与对象的继承层次关系:

注意:所有的metaclass中isa指针都是指向根metaclass,而根metaclass则指向自身。根metaclass是通过继承根类产生的,与根class结构体成员一致,不同的是根metaclass的isa指针指向自身。

1、当我们调用某个对象的对象方法时,它会首先在自身isa指针指向的类(class)methodLists中查找该方法,如果找不到则会通过class的super_class指针找到其父类,然后从其methodLists中查找该方法,如果仍然找不到,则继续通过 super_class向上一级父类结构体中查找,直至根class;

2、当我们调用某个类方法时,它会首先通过自己的isa指针找到metaclass,并从其methodLists中查找该类方法,如果找不到则会通过metaclass的super_class指针找到父类的metaclass结构体,然后从methodLists中查找该方法,如果仍然找不到,则继续通过super_class向上一级父类结构体中查 找,直至根metaclass;


四.下面我们来看一下代码实现:

1、创建一个类

CustomClass.h


[objc]  view plain copy print ?
  1. #import <Foundation/Foundation.h>  
  2.   
  3. @interface CustomClass : NSObject  
  4.   
  5. @property (nonatomic , strongNSString *age;  
  6.   
  7. - (void)test;  
  8.   
  9. @end  

CustomClass.m


[objc]  view plain copy print ?
  1. #import "CustomClass.h"  
  2.   
  3. @implementation CustomClass  
  4.   
  5. - (void)test  
  6. {  
  7.     NSLog(@"这里是CustomClass");  
  8.       
  9. }  
  10.   
  11. @end  

接下来创建一个类别来实现RunTime机制

NSObject+RunTimeTest.h


[objc]  view plain copy print ?
  1. #import <Foundation/Foundation.h>  
  2.   
  3. @interface NSObject (RunTimeTest)  
  4.   
  5. //动态创建一个类,之后为这个类的age属性赋值。  
  6. - (id) testRunTime:(NSString *)classname age:(NSString *)age;  
  7.   
  8.   
  9. @end  

NSObject+RunTimeTest.m


[objc]  view plain copy print ?
  1. #import "NSObject+RunTimeTest.h"  
  2. #import <objc/runtime.h>  
  3. #import "CustomClass.h"  
  4.   
  5.   
  6. @implementation NSObject (RunTimeTest)  
  7.   
  8. - (CustomClass *)testRunTime:(NSString *)classname age:(NSString *)age  
  9. {  
  10.     // propertyCount 成员属性的数量  
  11.     unsigned int propertyCount = 0;  
  12.     /* objc_property_t 根据苹果文档的解释:An opaque type that represents an Objective-C declared property. 
  13.   个人理解:一个任意类型的对象代表一个oc声明的属性成员 (本人英语水平实在有限)*/  
  14.     /* class_copyPropertyList   
  15.      文档:Return Value 
  16.      An array of pointers of type objc_property_t describing the properties declared by the class. Any properties declared by superclasses are not included. The array contains *outCount pointers followed by a NULL terminator. You must free the array with free(). 
  17.      个人理解:主要2个意思:返回一个数组指针,类型为objc_property_t,用完要记得free,释放掉。 
  18.      */  
  19.     objc_property_t *properties = class_copyPropertyList([self class], &propertyCount);  
  20.     for (unsigned int i = 0; i < propertyCount; i++) {  
  21.   objc_property_t property = properties[i];  
  22.   //获取成员的名称  
  23.   NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];  
  24.   NSLog(@"propertyName = %@ -- 成员名称",propertyName);  
  25.     
  26.   //获取成员内容的Ivar  
  27.   Ivar iVar = class_getInstanceVariable([self class], [propertyName UTF8String]);  
  28.   //其实上面那行获取代码是为了保险起见,基本是获取不到内容的。因为成员的名称默认会在前面加"_" ,  
  29.   if (iVar == nil) {  
  30.       iVar = class_getInstanceVariable([self class], [[NSString stringWithFormat:@"_%@",propertyName] UTF8String]);  
  31.   }  
  32.     
  33.   //  取值  
  34.   id propertyVal = object_getIvar(self, iVar);  
  35.   NSLog(@"propertyVal = %@ --值",propertyVal);  
  36.     
  37.          
  38.     
  39.     
  40.   // 动态创建类  
  41.   Class varClass = NSClassFromString(classname);  
  42.   id varObj = [[varClass alloc] init];  
  43.   //调用新创建类的方法,这里要主要一定引入对应得头文件,不然调用方法会不错。  
  44.   [varObj test];  
  45.     
  46.   Ivar iVarObj = class_getInstanceVariable(varClass, [@"_age" UTF8String]);  
  47.     
  48.     
  49.     
  50.   object_setIvar(varObj, iVarObj, age);  
  51.     
  52.     
  53.   return varObj;  
  54.     }  
  55.     return nil;  
  56.       
  57.       
  58.       
  59. }  
  60.   
  61. @end  

测试:

ViewController.m


[objc]  view plain copy print ?
  1. #import "NSObject+RunTimeTest.h"  
  2. #import "CustomClass.h"  
  3.   
  4. @interface ViewController ()  
  5.   
  6. @property (nonatomic , strongNSString *name;  
  7.   
  8.   
  9. @end  
  10.   
  11. @implementation ViewController  
  12.   
  13. - (void)viewDidLoad {  
  14.   [super viewDidLoad];  
  15.   // Do any additional setup after loading the view, typically from a nib.  
  16.     
  17.   _name = @"xiaonan";  
  18.   CustomClass *tmp = [self testRunTime:@"CustomClass" age:@"098"];  
  19.   NSLog(@"tmp.age = %@",tmp.age);  
  20.     
  21.     
  22. }  

结果输出:

[objc]  view plain copy print ?
  1. 2014-11-29 17:16:55.483 TestRunTime2[21001:176367] propertyName = name -- 成员名称  
  2. 2014-11-29 17:16:55.483 TestRunTime2[21001:176367] propertyVal = xiaonan --值  
  3. 2014-11-29 17:16:55.484 TestRunTime2[21001:176367] 这里是CustomClass  
  4. 2014-11-29 17:16:55.484 TestRunTime2[21001:176367] tmp.age = 098  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值