iOS-OC中 runtime 的基本使用

  • runtime,运行时机制,是一套C语言库
  • 实际上我们编写的所有OC代码,最终都是转成了runtime库的东西
  • 类转成了runtime库里面的结构体等数据类型,方法转成了runtime库里面的C语言函数,平时调方法都是转成了objc_msgSend函数
  • runtime是OC的底层实现,是OC的幕后执行者
  • runtime能获取类里面的所有成员变量,为类动态添加成员变量,动态改变类的方法实现,为类动态添加新的方法等
  • KVO是基于runtime机制实现的
  • 字典转模型也是通过runtime实现的

下面讲解runtime的具体运用

准备工作,创建一个Dog类

@interface Dog : NSObject

- (void)run;
+ (void)est;

@end

-----------------------------------------------------
@implementation Dog

- (void)run {
    NSLog(@"小狗快跑");
}

- (void)eat {
    NSLog(@"小狗快吃");
}
@end

1、发送消息

// 创建对象
Dog *dog = [[Dog alloc] init];
// 调用对象方法
[dog run]; // 打印:小狗快跑
// 本质:让对象发送消息
objc_msgSend(dog,@selector(run)); // 打印:小狗快跑

2、交换方法

// 获取实例方法
Method run = class_getInstanceMethod([Dog class], @selector(run));
// 获取类方法
Method eat = class_getClassMethod([Dog class], @selector(eat));
// 交换方法
method_exchangeImplementations(run, eat);
// 执行交换后的方法
[dog run]; // 打印:小狗快吃
[Dog eat]; // 打印:小狗快跑

3、获取列表

获取属性列表
unsigned int count;
// 获取属性列表
objc_property_t *propertyList = class_copyPropertyList([UITextField class], &count);
for (unsigned int i = 0; i < count; i++) {
     const char *propertyName = property_getName(propertyList[i]);
    NSLog(@"PropertyName--->%@",[NSString stringWithUTF8String:propertyName]);
}
获取方法列表
unsigned int count;
// 获取方法列表
Method *methodList = class_copyMethodList([UIButton class], &count);
for (unsigned int i = 0; i < count; i++) {
    Method method = methodList[i];
    NSLog(@"Method--->%@",NSStringFromSelector(method_getName(method)));
}
获取成员变量列表
unsigned int count;
// 获取成员变量列表
Ivar *ivarList = class_copyIvarList([UISearchBar class], &count);
for (unsigned int i = 0; i < count; i++) {
    Ivar ivar = ivarList[i];
    const char *ivarName = ivar_getName(ivar);
    NSLog(@"Ivar--->%@",[NSString stringWithUTF8String:ivarName]);
}
free(ivarList);
获取协议列表
unsigned int count;
// 获取协议列表
__unsafe_unretained Protocol **protocolList = class_copyProtocolList([UITableView class], &count);
for (unsigned int i = 0; i < count; i++) {
    Protocol *protocol = protocolList[i];
    const char *protocolName = protocol_getName(protocol);
    NSLog(@"ProtocolName--->%@",[NSString stringWithUTF8String:protocolName]);
}

4、关联对象

// 首先定义一个全局变量,用它的地址作为关联对象的key
static char associatedObjectKey;
// 设置关联对象
objc_setAssociatedObject(dog, &associatedObjectKey, @"添加的字符串属性", OBJC_ASSOCIATION_RETAIN_NONATOMIC); //获取关联对象
NSString *string = objc_getAssociatedObject(dog, &associatedObjectKey);
NSLog(@"AssociatedObject = %@", string);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值