Last active
August 29, 2015 13:57
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NSObject+SimpleObjectMapping
A simple class extension to do a simple thing:
SetValue:ForUndefinedKey:
exception for you.note: The keys in the dictionary must match your property names
Usage:
Simple.