Save CoreData-entities in NSUserDefaults
If you need to store a reference to a specific managed object, use the URI representation of its managed object ID:
NSURL *moIDURL = [[myManagedObject objectID] URIRepresentation];
You can then save the URL to user defaults.
To retrieve the managed object, you use:
NSManagedObjectID *moID = [myPersistentStoreCoordinator managedObjectIDForURIRepresentation:moIDURL];
NSManagedObject *myManagedObject = [myContext objectWithID:moID];
The only caveat is that you must ensure that the original managed object ID is permanent -- this is not a problem if you've already saved the object, alternatively you can use obtainPermanentIDsForObjects:error:
.
Here's the cleanest and shortest way to currently do this using the setURL and getURL methods added in 4.0 to avoid extra calls to NSKeyedUnarchiver and NSKeyedArchiver:
Setter:
+ (void)storeSomeObjectId:(NSManagedObjectID *)objectId
{
[[NSUserDefaults standardUserDefaults] setURL:[objectId URIRepresentation]
forKey:@"someObjectIdKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
Getter:
+ (SomeManagedObject *)getObjectByStoredId
{
NSURL *uri = [[NSUserDefaults standardUserDefaults] URLForKey:@"someObjectIdKey"];
NSManagedObjectID *objectId = [self.persistentStoreCoordinator managedObjectIDForURIRepresentation:uri];
SomeManagedObject *object = [self.managedObjectContext objectWithID:objectId];
}
You wouldn't want to try and archive a core data entity and store it. Instead, you would store the key or some other known attribute and use it to fetch the entity when the application starts up.
Some example code (slightly modified from the example posted in the Core Data Programming Guide):
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:@"SearchEngine" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"engineName LIKE[c] '%@'", selectedEngineName];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil)
{
// Deal with error...
}
This way you save the name in the user defaults and fetch the entity when necessary.