Method 1:
Use the objective-C nsobject built-in method
Setvaluesforkeyswithdictionary: dict
If the key in nsdictionary has the same attribute name as the object class object, set the value of the key to the attribute corresponding to the object class.
- (instancetype)initWithDict:(NSDictionary *)dict{ if (self = [super init]) { [self setValuesForKeysWithDictionary:dict]; } return self;}
Method 2: detailed methods on the Internet
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;}
Convert nsdictionary to Object Class Object