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

245 阅读1分钟

首先创建一个字典:


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 <objc/runtime.h>

@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<outCount; i++) {

        //获取属性名字符串
        objc_property_t property = arrPropertys[i];

        //model中的属性名
        NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];

        id propertyValue = dic[propertyName];
        if (propertyValue != nil) {
            [myObj setValue:propertyValue forKey:propertyName];
        }

    }

    //注意在runtime获取属性的时候,并不是arc 需要释放
    free(arrPropertys);
    return myObj;

}


@end

使用实例


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

TestModel *model = [TestModel initWithDictionaryForModel:dict];

打个断点看下结果:

Untitled.png