方法一:
使用objective-c NSObject自带的方法
setValuesForKeysWithDictionary:dict
作用是: 如果NSDictionary中的key和实体类对象的属性名相同, 那么把该key的value 设置到实体类对应的属性
- (instancetype)initWithDict:(NSDictionary *)dict { if (self = [super init]) { [self setValuesForKeysWithDictionary:dict]; } return self; }
方法二: 网上的细化的方法
http://www.cocoachina.com/bbs/simple/?t97803.html
#import <objc/runtime.h> -(NSString *) className { return NSStringFromClass([self class]); } - (void)objectFromDictionary:(NSDictionary*) dict { unsigned int propCount, i; objc_property_t* properties = class_copyPropertyList([self class], &propCount); for (i = 0; i < propCount; i++) { objc_property_t prop = properties; const char *propName = property_getName(prop); if(propName) { NSString *name = [NSString stringWithCString:propName encoding:NSUTF8StringEncoding]; id obj = [dict objectForKey:name]; if (!obj) continue; if ([[obj className] isEqualToString:@"__NSCFString"] || [[obj className] isEqualToString:@"__NSCFNumber"]) { [self setValue:obj forKeyPath:name]; } else if ([obj isKindOfClass:[NSDictionary class]]) { id subObj = [self valueForKey:name]; if (subObj) [subObj objectFromDictionary:obj]; } } } free(properties); } - (id)initWithDictionary:(NSDictionary*) dict { self = [self init]; if(self && dict) [self objectFromDictionary:dict]; return self; }