首页 > 代码库 > NSDictionary转化为实体类对象
NSDictionary转化为实体类对象
方法一:
使用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;}
NSDictionary转化为实体类对象
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。