- 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);