IOS - - 字典转模型

新建模型基类BaseModel
在BaseModel.h中声明如下方法:
-(instancetype)initWithjsonDictionary:(NSDictionary*)jsonDictionary;

.m中实现:

-(instancetype)initWithjsonDictionary:(NSDictionary*)jsonDictionary{
    self = [super init];
    if (self) {
        [self setValuesForKeysWithDictionary:jsonDictionary];
    }
    return self;
}

但是要注意当字典中有的键值对而model中没有时会出现异常,导致程序崩溃,可以实现如下方法避免崩溃:

-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
    NSLog(@"%@模型中没有%@属性字段",NSStringFromClass([self class]),key);
}

当遇到未定义的字段时会打印如下log

posted @ 2017-09-18 11:45  熹微_念  阅读(258)  评论(0编辑  收藏  举报