关于runtime的知识已经有不少的讲解(传送门:对runtime的理解 http://www.jianshu.com/p/927c8384855a),但一直不知道runtime的使用场景, 接下来利用runtime实现将字典转换成model。但愿你们对runtime的使用有个初步了解。测试
首先定义个RuntimeModel 类atom
//RuntimeModel.h #import <Foundation/Foundation.h> #import <objc/runtime.h> //别忘记引入库 @interface RuntimeModel : NSObject -(instancetype)initWithDic :(NSDictionary *)dic; @end //RuntimeModel.m -(instancetype)initWithDic :(NSDictionary *)dic { self = [super init]; if (self) { NSMutableArray * keyArray = [NSMutableArray array]; NSMutableArray * attributeArray = [NSMutableArray array]; unsigned int outCount = 0 ; objc_property_t * propertys = class_copyPropertyList([self class], &outCount); //获取该类的属性列表 for (int i = 0 ; i < outCount; i++) { objc_property_t property = propertys[i]; NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; //获取属性对应的名称 [keyArray addObject:propertyName]; } free(propertys); //记得要释放 for (NSString * key in keys) { if (![keyArray containsObject:key]||[dic valueForKey:key] == nil) continue ; [self setValue:[dic valueForKey:key] forKey:key]; } } return self; }
而后咱们建立个model继承RuntimeModel类,并添加属性spa
// DataModel.h #import <Foundation/Foundation.h> #import "RuntimeModel.h" @interface DataModel : RuntimeModel @property (nonatomic , strong)NSString * name ; @property (nonatomic , strong)NSString * imageUrl;
接下来能够在ViewController里调用试试结果code
- (void)viewDidLoad { [super viewDidLoad]; NSDictionary * dic = [[NSDictionary alloc]initWithObjectsAndKeys:@"测试",@"name",@"图片连接",@"imageUrl", nil]; DataModel * model = [[DataModel alloc]initWithDic:dic]; NSLog(@"name --%@ , imageUrl --%@",model.name ,model.imageUrl); }
测试结果是继承
2016-03-25 11:21:49.626 Wheat[750:64557] name --测试 , imageUrl --图片连接图片