Skip to content

Instantly share code, notes, and snippets.

@jdriscoll
Created July 30, 2013 13:30
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jdriscoll/6112908 to your computer and use it in GitHub Desktop.
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.
//
// 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
//
// 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