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

原文地址:https://www.cnblogs.com/zhhl/p/7542322.html