码迷,mamicode.com
首页 > 其他好文 > 详细

NSDictionary转化为实体类对象

时间:2014-10-12 12:13:07      阅读:1833      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   使用   ar   for   

方法一: 

使用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转化为实体类对象

标签:style   blog   http   color   io   os   使用   ar   for   

原文地址:http://www.cnblogs.com/apem/p/4020324.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!