Created
October 25, 2013 23:44
-
-
Save priore/7163520 to your computer and use it in GitHub Desktop.
Set property values from a NSDictionary
This file contains hidden or 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
| // | |
| // NSObject+NSDictionary.h | |
| // | |
| @interface NSObject (NSDictionary) | |
| - (void)setValuesWithDictionary:(NSDictionary*)dict; | |
| @end | |
| // | |
| // NSObject+NSDictionary.m | |
| // | |
| #import "NSObject+NSDictionary.h" | |
| #import <objc/runtime.h> | |
| @implementation NSObject (NSDictionary) | |
| - (void)setValuesWithDictionary:(NSDictionary*)dict | |
| { | |
| unsigned int count = 0; | |
| objc_property_t *properties = class_copyPropertyList([self class], &count); | |
| for (int i = 0; i < count; ++i) { | |
| objc_property_t property = properties[i]; | |
| NSString *name = [NSString stringWithCString:property_getName(properties[i]) encoding:NSUTF8StringEncoding]; | |
| if ([dict.allKeys indexOfObject:name] != NSNotFound) { | |
| NSArray *propertyAttributes = [[[[NSString alloc] initWithUTF8String:property_getAttributes(property)] autorelease] componentsSeparatedByString:@","]; | |
| if ([propertyAttributes indexOfObject:@"R"] == NSNotFound) { | |
| if ([propertyAttributes indexOfObject:@"T@\"NSString\""] != NSNotFound) { | |
| [self setValue:[dict objectForKey:name] forKey:name]; | |
| } else if ([propertyAttributes indexOfObject:@"Ti"] != NSNotFound) { // integer | |
| [self setValue:@([[dict objectForKey:name] integerValue]) forKey:name]; | |
| } else if ([propertyAttributes indexOfObject:@"Tf"] != NSNotFound) { // float | |
| [self setValue:@([[dict objectForKey:name] floatValue]) forKey:name]; | |
| } else if ([propertyAttributes indexOfObject:@"Td"] != NSNotFound) { // double | |
| [self setValue:@([[dict objectForKey:name] doubleValue]) forKey:name]; | |
| } else if ([propertyAttributes indexOfObject:@"Tl"] != NSNotFound) { // long | |
| [self setValue:@([[dict objectForKey:name] longValue]) forKey:name]; | |
| } else if ([propertyAttributes indexOfObject:@"Ts"] != NSNotFound) { // short | |
| [self setValue:@([[dict objectForKey:name] shortValue]) forKey:name]; | |
| } else if ([propertyAttributes indexOfObject:@"Tc"] != NSNotFound) { // bool YES/NO (char ???) | |
| [self setValue:@([[dict objectForKey:name] boolValue]) forKey:name]; | |
| } | |
| } | |
| } | |
| } | |
| free(properties); | |
| } | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment