OC语言基础十四:Runtime

简介

Runtime 是一套由C语言API组合成的Runtime库,偏底层,执行效率也会高一些。
Runtime 会尽可能把代码的执行决策推迟到运行时,一段代码真正的执行结果可能要到运行时才能真正体现出来
OC是动态语言,OC代码最终都会转换成底层Runtime的代码

如:[person setAge:10];转换成
objc_msgSend(person,@selector(setAge:),10);//向person发送消息,第一个是消息的接收者,第二个是消息名称,第三个是传入参数。

使用

#import<objc/runtime.h>
动态获取/创建类
动态为一个类增加属性或方法
在程序运行时遍历类中的实例变量,属性或方法
调换2个方法的逻辑实现。

动态获取对象的类型

Person *person=[Person person];
NSLog(@"%@",[person class]);

遍历实例变量

Class personClass=person.class;
unsigned int outCount=0;
Ivar *ivarPtr=class_copyIvarList(personClass,&outCount);
for(NSInteger i=0;i< outCount;i++){
   Ivar ivar=ivarPtr[i];
   NSLog(@"实例变量:%s",ivar_getName(ivar));
}

输出:_name和_age

遍历属性

objc_property_t   *propertyPtr=class_copyPropertyList(personClass,&outCount);
for(NSInteger i=0;i<outCount;i++){
objc_property_t  property=propertyPtr[i];
NSLog(@"属性:%s",property_getName(property));
}

返回:name和age

遍历方法

SEL selctor不能直接打印,需要用到,NSStringFromSelector(selector);

Method *methodPtr=class_copyMethodList(personClass,&outCount);
for(NSInteger i=0;i<outCount;i++){
Method method=methodPtr[i];
SEL selector=method_getName(method);
NSLog(@"%@",NSStringFromSelector(selector));
}

输出:setName:,name,age,setAge:,.cxx_destruct(隐藏的一个函数,和类的销毁有关)
在这里插入图片描述

消息发送的底层实现函数

设置:
添加#import<objc/message.h>
如果该项是YES,会报错。
在这里插入图片描述
实现是等价的,下面是上面的底层实现函数

[person setAge:10];
objc_msgSend(person,@selector(setAge:),10);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值