关于runtime的知识已经有很多的讲解(传送门:对runtime的理解 http://www.jianshu.com/p/927c8384855a),但一直不知道runtime的使用场景, 接下来利用runtime实现将字典转换成model。希望大家对runtime的使用有个初步了解。
首先定义个RuntimeModel 类
1//RuntimeModel.h 2#import <Foundation/Foundation.h> 3#import <objc/runtime.h> //别忘记引入库 4@interface RuntimeModel : NSObject 5 6-(instancetype)initWithDic :(NSDictionary *)dic; 7 8@end 9 10 11//RuntimeModel.m 12-(instancetype)initWithDic :(NSDictionary *)dic { 13 self = [super init]; 14 if (self) { 15 NSMutableArray * keyArray = [NSMutableArray array]; 16 NSMutableArray * attributeArray = [NSMutableArray array]; 17 unsigned int outCount = 0 ; 18 objc_property_t * propertys = class_copyPropertyList([self class], &outCount); //获取该类的属性列表 19 for (int i = 0 ; i < outCount; i++) { 20 objc_property_t property = propertys[i]; 21 NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; //获取属性对应的名称 22 [keyArray addObject:propertyName]; 23 } 24 free(propertys); //记得要释放 25 for (NSString * key in keys) { 26 27 if (![keyArray containsObject:key]||[dic valueForKey:key] == nil) continue ; 28 [self setValue:[dic valueForKey:key] forKey:key]; 29 } 30 } 31 return self; 32}
然后我们创建个model继承RuntimeModel类,并添加属性
1// DataModel.h 2#import <Foundation/Foundation.h> 3#import "RuntimeModel.h" 4@interface DataModel : RuntimeModel 5@property (nonatomic , strong)NSString * name ; 6@property (nonatomic , strong)NSString * imageUrl;
接下来可以在ViewController里调用试试结果
1- (void)viewDidLoad { 2 [super viewDidLoad]; 3 NSDictionary * dic = [[NSDictionary alloc]initWithObjectsAndKeys:@"测试",@"name",@"图片链接",@"imageUrl", nil]; 4 DataModel * model = [[DataModel alloc]initWithDic:dic]; 5 NSLog(@"name --%@ , imageUrl --%@",model.name ,model.imageUrl); 6 }
测试结果是
**2016-03-25 11:21:49.626 Wheat[750:64557] name --**测试 **, imageUrl --**图片链接