Created
July 30, 2013 13:30
-
-
Save jdriscoll/6112908 to your computer and use it in GitHub Desktop.
NSManagedObject to JSON-ready dictionary and back again (Does not handle relationships). Uses https://gist.github.com/jdriscoll/6112942.
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
// | |
// NSManagedObject+JSON.h | |
// Rego | |
// | |
// Created by Justin Driscoll on 7/29/13. | |
// Copyright (c) 2013 Makalu Inc. All rights reserved. | |
// | |
#import <CoreData/CoreData.h> | |
@interface NSManagedObject (JSON) | |
- (NSDictionary *)dictionaryOfAttributes:(NSSet *)excludedKeys; | |
- (void)updateAttributesFromDictionary:(NSDictionary *)attributesDictionary; | |
@end |
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
// | |
// NSManagedObject+JSON.m | |
// Rego | |
// | |
// Created by Justin Driscoll on 7/29/13. | |
// Copyright (c) 2013 Makalu Inc. All rights reserved. | |
// | |
#import "NSManagedObject+JSON.h" | |
#import "NSDate+Formats.h" | |
@implementation NSManagedObject (JSON) | |
- (NSDictionary *)dictionaryOfAttributes:(NSSet *)excludedKeys | |
{ | |
NSMutableDictionary *data = [NSMutableDictionary dictionary]; | |
NSDictionary *attributes = [[self entity] attributesByName]; | |
for (NSString *key in [attributes allKeys]) { | |
if ([excludedKeys containsObject:key]) | |
continue; | |
id value = [self valueForKey:key]; | |
if (!value) | |
continue; | |
if ([value isKindOfClass:[NSDate class]]) { | |
value = [(NSDate *)value toJSONDate]; | |
} | |
data[key] = value; | |
} | |
return data; | |
} | |
- (void)updateAttributesFromDictionary:(NSDictionary *)attributesDictionary | |
{ | |
for (NSString *key in [attributesDictionary allKeys]) { | |
id value = attributesDictionary[key]; | |
if ([value isKindOfClass:[NSString class]]) { | |
NSDate *dateValue = [NSDate fromJSONDate:value]; | |
if (dateValue) { | |
value = dateValue; | |
} | |
} | |
[self setValue:value forKey:key]; | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment