利用运行时给模型赋值
前提是模型属性和key要一致 下面的代码只需要修改这个类方法就可以用了
+(instancetype)userCommentsWithDict:(NSDictionary *)dict{
id obj = [[self alloc]init]; NSArray *array =[self loadProperties]; for (NSString *key in array) { if (dict[key]) { [obj setValue:dict[key] forKey:key]; } } return obj;}+ (NSArray *)loadProperties { unsigned int count = 0; // 返回值是所有属性的数组 objc_property_t *properties = class_copyPropertyList([self class], &count); NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:count]; for (int i = 0; i < count; ++i) { // 1. 从数组中获得属性 objc_property_t pty = properties[i]; // 2. 拿到属性名称 const char *cname = property_getName(pty); [arrayM addObject:[NSString stringWithUTF8String:cname]]; } // 释放属性数组 free(properties); return arrayM;}