iOS底层原理笔记 - Runtime应用02-字典转模型

Runtime应用02-字典转模型

首先创建一个字典:

NSDictionary *dict = @{
    @"name":@"jack",
    @"address":@"beijingbeijing",
    @"phone":@"13111122211",
    @"age":@12,
    @"weight":@45,
    @"height":@170,
};

根据key来记录property的属性名称,创建一个模型:

@interface TestModel : NSObject

@property(nonatomic, copy) NSString *name;
@property(nonatomic, copy) NSString *address;
@property(nonatomic, copy) NSString *phone;
@property(nonatomic, assign) NSInteger age;
@property(nonatomic, assign) NSInteger weight;
@property(nonatomic, assign) NSInteger height;

@end

然后创建一个NSObject的分类,当我们要使用的时候直接导入就可以使用:

@interface NSObject (Model)

+ (instancetype)initWithDictionaryForModel:(NSDictionary *)dic;

@end

根据runtime来进行赋值:

#import "NSObject+Model.h"
#import 

@implementation NSObject (Model)

+ (instancetype)initWithDictionaryForModel:(NSDictionary *)dic {
    id myObj = [[self alloc] init];
    unsigned int outCount;
    //获取类中所有成员属性
    objc_property_t *arrPropertys = class_copyPropertyList([self class], &outCount);
    for (NSInteger i=0; i

使用实例

NSDictionary *dict = @{
            @"name":@"jack",
            @"address":@"beijingbeijing",
            @"phone":@"13111122211",
            @"age":@12,
            @"weight":@45,
            @"height":@170,
};
TestModel *model = [TestModel initWithDictionaryForModel:dict];

打个断点看下结果:

Untitled.png

你可能感兴趣的:(iOS底层原理笔记 - Runtime应用02-字典转模型)