<!--Person.h文件-->
@interface Person : NSObject
{
NSString *address;
}
@property(nonatomic,strong)NSString *name;
@property(nonatomic,assign)NSInteger age;
//遍历获取所有属性Property
- (void) getAllProperty {
unsigned int propertyCount = 0;
objc_property_t *propertyList = class_copyPropertyList([Person class], &propertyCount);
for (unsigned int i = 0; i < propertyCount; i++ ) {
objc_property_t *thisProperty = propertyList[i];
const char* propertyName = property_getName(*thisProperty);
NSLog(@"Person拥有的属性为: '%s'", propertyName);
}
}
<!--打印结果-->
2016-06-15 20:25:19.653 demo-Cocoa之method swizzle[17778:2564081] Person拥有的属性为: 'name'
2016-06-15 20:25:19.653 demo-Cocoa之method swizzle[17778:2564081] Person拥有的属性为: 'age'
应用具体场景
1、Json到Model的转化
在开发中相信最常用的就是接口数据需要转化成Model了(当然如果你是直接从Dict取值的话。。。),很多开发者也都使用著名的第三方库如JsonModel、Mantle或MJExtension等,如果只用而不知其所以然,那真和“搬砖”没啥区别了,下面我们使用runtime去解析json来给Model赋值。
原理描述:用runtime提供的函数遍历Model自身所有属性,如果属性在json中有对应的值,则将其赋值。
核心方法:在NSObject的分类中添加方法:
- (instancetype)initWithDict:(NSDictionary *)dict {
if (self = [self init]) {
//(1)获取类的属性及属性对应的类型
NSMutableArray * keys = [NSMutableArray array];
NSMutableArray * attributes = [NSMutableArray array];
/*
* 例子
* name = value3 attribute = T@"NSString",C,N,V_value3
* name = value4 attribute = T^i,N,V_value4
*/
unsigned int outCount;
objc_property_t * properties = class_copyPropertyList([self class], &outCount);
for (int i = 0; i < outCount; i ++) {
objc_property_t property = properties[i];
//通过property_getName函数获得属性的名字
NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
[keys addObject:propertyName];
//通过property_getAttributes函数可以获得属性的名字和@encode编码
NSString * propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
[attributes addObject:propertyAttribute];
}
//立即释放properties指向的内存
free(properties);
//(2)根据类型给属性赋值
for (NSString * key in keys) {
if ([dict valueForKey:key] == nil) continue;
[self setValue:[dict valueForKey:key] forKey:key];
}
}
return self;
}
读者可以进一步思考:
如何识别基本数据类型的属性并处理










