Skip to content

Instantly share code, notes, and snippets.

@johnhatvani
Last active August 29, 2015 13:57
Show Gist options
  • Save johnhatvani/9405470 to your computer and use it in GitHub Desktop.
Save johnhatvani/9405470 to your computer and use it in GitHub Desktop.
Simple Object Mapper. A category on NSObject that will construct a instance of your class and assign all values from the dictionary using KVC (make sure your property names are the same as the keys in the dictionary)
#import <objc/runtime.h>
@implementation NSObject (SimpleObjectMapping)
+ (instancetype) objectFromDictionary:(NSDictionary *)dictionary {
NSObject *instance = [[self.class alloc] init];
objc_property_t *properties = class_copyPropertyList(self.class, NULL);
objc_property_t property;
while ((property = *properties ++) != nil) {
NSString *key = [NSString stringWithUTF8String:property_getName(property)];
id<NSObject> value = nil;
if ((value = dictionary[key])) {
[instance setValue:value forKey:key];
}
}
return instance;
}
@johnhatvani
Copy link
Author

NSObject+SimpleObjectMapping

A simple class extension to do a simple thing:

  • Take a dictionary
  • Assign the values from the dictionary to properties in your object via KVC
  • Safe -- no SetValue:ForUndefinedKey: exception for you.

note: The keys in the dictionary must match your property names

Usage:

//...
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:options error:&error];
MyObject *obj = [MyObject objectFromDictionary:json];

Simple.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment