runtime学习笔记

时间:2022-01-17 00:11:58

获取属性
objc_property_t * propertys = class_copyPropertyList(clazz, &outCount);

获取属性名
NSString * key = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];

获取属性的描述
NSString * attributesString = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];

获取方法
Method * methods = class_copyMethodList(clazz, &outCount);

获取方法名
NSStringFromSelector(method_getName(method));

获取成员变量
Ivar * vars = class_copyIvarList(clazz,&outCount);

获取成员变量名
NSString * varName = [NSString stringWithCString:ivar_getName(var) encoding:NSUTF8StringEncoding];

使用runtime的方式执行方法调用

objc_msgSend(p, @selector(setAge:),20);

- (void)my_setValue:(id)value forKeyPath:(NSString *)keyPath
{

id obj = self;

// 将keyPath中的属性逐个分开存到数组中
NSArray * array = [keyPath componentsSeparatedByString:@"."];

// 获得最后一个属性
NSString * propertyName = [array lastObject];

// 遍历得到最后一个属性的get方法
for(NSUInteger i = 0; i < array.count - 1; i++)
{

SEL getSel = NSSelectorFromString(array[i]);

obj = objc_msgSend(obj, getSel);

}

propertyName = [NSString stringWithFormat:@"set%@:", [propertyName capitalizedString]];

SEL setSel = NSSelectorFromString(propertyName);

// 发送消息调用set方法赋值
objc_msgSend(obj, setSel, value);

}