利用Runtime解析类的属性Property
1 获取类的属性列表class_copyPropertyList()
///以Person为例
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSDate *birthday;
@property (nonatomic, assign) uint8 age;
@end
2 获取属性名称:property_getName()
3 获取属性的属性字符串:property_getAttributes()
+ (void)run {
unsigned int count = 0;
objc_property_t *propertys = class_copyPropertyList([Person class], &count);
for (int i = 0; i < count; i ++) {
objc_property_t property = propertys[i];
if (property == nil) {
continue;
}
NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
NSLog(@"propertyName=%@",propertyName);
NSString *propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
NSLog(@"propertyAttribute=%@",propertyAttribute);
}
free(propertys);
}
打印结果:
2019-04-12 21:59:15.400128+0800 property[32964:10800666] propertyName=name
2019-04-12 21:59:15.400385+0800 property[32964:10800666] propertyAttribute=T@"NSString",C,N,V_name
2019-04-12 21:59:15.400405+0800 property[32964:10800666] propertyName=birthday
2019-04-12 21:59:15.400433+0800 property[32964:10800666] propertyAttribute=T@"NSDate",&,N,V_birthday
2019-04-12 21:59:15.400462+0800 property[32964:10800666] propertyName=age
2019-04-12 21:59:15.400485+0800 property[32964:10800666] propertyAttribute=TC,N,V_age
解析含义:property_getName()
获取的是属性的名称,这个无可厚非
property_getAttribute()
返回的字符串T@"NSDate",&,N,V_birthday
是什么含义呢?
解析一下
T后边的是属性的类型也就是NSDate类型的属性
N代表nonatomic也就是非原子性
V后边的是属性对应的变量名_birthday,是否回想到OC的属性和成员变量是一一对应的,只是自动生成了setter和getter函数,而成员变量也就是下划线那个。具体含义对应表:
参考文献
Apple官网