Skip to content

Instantly share code, notes, and snippets.

@soffes
Created February 28, 2010 21:06
Show Gist options
  • Save soffes/317794 to your computer and use it in GitHub Desktop.
Save soffes/317794 to your computer and use it in GitHub Desktop.
+ (AppDelegate *)sharedAppDelegate {
return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
[[[AppDelegate sharedAppDelegate] managedObjectContext] save:nil];
NSData *archivedObjects = [NSKeyedArchiver archivedDataWithRootObject:objects];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:archivedObjects forKey:@"someKey"];
[userDefaults synchronize];
//
// SSManagedObject.h
// Archiving NSManagedObject with NSCoding
//
// Created by Sam Soffes on 2/28/10.
// Copyright 2010 Sam Soffes. All rights reserved.
//
@interface SSManagedObject : NSManagedObject <NSCoding> {
}
+ (NSManagedObjectContext *)mainContext;
@end
//
// SSManagedObject.m
// Archiving NSManagedObject with NSCoding
//
// Created by Sam Soffes on 2/28/10.
// Copyright 2010 Sam Soffes. All rights reserved.
//
#import "SSManagedObject.h"
#import "AppDelegate.h"
static NSString *const kURIRepresentationKey = @"URIRepresentation";
@implementation SSManagedObject
#pragma mark - Class Methods
+ (NSManagedObjectContext *)mainContext {
AppDelegate *appDelegate = [AppDelegate sharedAppDelegate];
return [appDelegate managedObjectContext];
}
#pragma mark - NSCoding
- (id)initWithCoder:(NSCoder *)decoder {
NSManagedObjectContext *context = [[self class] mainContext];
NSPersistentStoreCoordinator *psc = [context persistentStoreCoordinator];
self = (SSManagedObject *)[[context objectWithID:[psc managedObjectIDForURIRepresentation:(NSURL *)[decoder decodeObjectForKey:kURIRepresentationKey]]] retain];
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:[[self objectID] URIRepresentation] forKey:kURIRepresentationKey];
}
@end
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSData *objectsData = [userDefaults objectForKey:@"someKey"];
if ([objectsData length] > 0) {
NSArray *objects = [NSKeyedUnarchiver unarchiveObjectWithData:objectsData]];
}
@azone
Copy link

azone commented Apr 18, 2013

Very useful, Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment