关于runtime的知识已经有很多的讲解(传送门:对runtime的理解 http://www.jianshu.com/p/927c8384855a),但一直不知道runtime的使用场景, 接下来利用runtime实现将字典转换成model。希望大家对runtime的使用有个初步了解。
首先定义个RuntimeModel 类
//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类,并添加属性
// DataModel.h
#import <Foundation/Foundation.h>
#import "RuntimeModel.h"
@interface DataModel : RuntimeModel
@property (nonatomic , strong)NSString * name ;
@property (nonatomic , strong)NSString * imageUrl;
接下来可以在ViewController里调用试试结果
- (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 --图片链接
来源:oschina
链接:https://my.oschina.net/u/2500207/blog/647159