-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNSManagedObject+safeSetValuesForKeysWithDictionary.m
44 lines (39 loc) · 1.89 KB
/
NSManagedObject+safeSetValuesForKeysWithDictionary.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//
// NSManagedObject+ safeSetValuesForKeysWithDictionary.m
// Youboox
//
// Created by Vincent Daubry on 13/07/13.
//
//
#import "NSManagedObject+safeSetValuesForKeysWithDictionary.h"
@implementation NSManagedObject (safeSetValuesForKeysWithDictionary)
- (void)safeSetManagedValuesForKeysWithDictionary:(NSDictionary *)keyedValues dateFormatter:(NSDateFormatter *)dateFormatter
{
NSDictionary *attributes = [[self entity] attributesByName];
for (NSString *attribute in attributes) {
id value = [keyedValues objectForKey:attribute];
if (value == nil) {
continue;
}
NSAttributeType attributeType = [[attributes objectForKey:attribute] attributeType];
if ((attributeType == NSStringAttributeType) && ([value isKindOfClass:[NSNumber class]])) {
value = [value stringValue];
} else if (((attributeType == NSInteger16AttributeType) || (attributeType == NSInteger32AttributeType) || (attributeType == NSInteger64AttributeType) || (attributeType == NSBooleanAttributeType)) && ([value isKindOfClass:[NSString class]])) {
value = [NSNumber numberWithInteger:[value integerValue]];
} else if ((attributeType == NSFloatAttributeType) && ([value isKindOfClass:[NSString class]])) {
value = [NSNumber numberWithDouble:[value doubleValue]];
} else if ((attributeType == NSDateAttributeType) && ([value isKindOfClass:[NSString class]]) && (dateFormatter != nil)) {
value = [dateFormatter dateFromString:value];
}
//We don't handle nested object yet
else if ((attributeType == NSStringAttributeType) && ([value isKindOfClass:[NSDictionary class]])) {
value = nil;
}
//Convert NSNull to nil
else if ([value isKindOfClass:[NSNull class]]) {
value = nil;
}
[self setValue:value forKey:attribute];
}
}
@end