-
-
Save jakehawken/79d8d5d28546ace743bca4c8160f36b5 to your computer and use it in GitHub Desktop.
@implementation NSObject (DataMapping) | |
- (instancetype)initByAutoMappingFromDictionary:(NSDictionary *)dictionary | |
{ | |
Class thisClass = [self class]; | |
self = [thisClass init]; | |
if (self) | |
{ | |
[self mapDictionaryValues:dictionary]; | |
} | |
return self; | |
} | |
- (void)mapDictionaryValues:(NSDictionary *)dictionary | |
{ | |
NSArray *dictKeys = [dictionary allKeys]; | |
for (NSString *key in dictKeys) | |
{ | |
[self attemptToSetPropertyWithObject:dictionary[key] forKey:key]; | |
} | |
} | |
#pragma - mark private / helper methods | |
- (void)attemptToSetPropertyWithObject:(NSObject *)object forKey:(NSString *)key | |
{ | |
SEL selectorFromString = [self setterSelectorFromKeyString:key]; | |
if ([self respondsToSelector:selectorFromString]) | |
{ | |
[self performSelector:selectorFromString withObject:object]; | |
} | |
} | |
- (SEL)setterSelectorFromKeyString:(NSString *)inputString | |
{ | |
NSString *capitalizedString = [inputString capitalizedString]; | |
NSString *selectorString = [NSString stringWithFormat:@"set%@:", capitalizedString]; | |
return NSSelectorFromString(selectorString); | |
} | |
@end |
I see you're stripping out spaces. What is the goal of your method? Isn't the onus on the caller to provide valid inputs? There's a whole host of invalid characters (including the +[NSCharacterSet whitespaceCharacterSet]
) the caller could provide. Are you sure accounting for these rules is something you want to take the burden of?
Shouldn't you call self = [super init] in your initializer? In fact, you don't want to call +alloc again because your object is already allocated.
Very good point.
I see you're stripping out spaces. What is the goal of your method? Isn't the onus on the caller to provide valid inputs? There's a whole host of invalid characters (including the +[NSCharacterSet whitespaceCharacterSet]) the caller could provide. Are you sure accounting for these rules is something you want to take the burden of?
Also a great point.
Shouldn't you call
self = [super init]
in your initializer? In fact, you don't want to call+alloc
again because your object is already allocated.