Convert nsdictionary to Object Class Object

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.