How can I use Core Data objects outside of the context of a managed object?

I would like to use Core Data managed objects outside of the managed object context. I've seen other threads on this site that say you should never do this, but here's my problem:

I have a Feed object and a story object. The Feed is like an RSS feed and the story is like one story from that feed. I have the ability to bookmark feeds and use Core Data to save them, but when I load stories from a feed, I don't want to insert those stories into the context of the managed object. The only way to create my objects, however, is this:

[NSEntityDescription insertNewObjectForEntityForName:name inManagedObjectContext:managedObjectContext];

      

This means it will be saved on the next save event.

I don't want these objects to persist until the user selects them.

I tried to define "TransientStory" and "PersistentStory" with the "Story" protocol they both implement, but this is a nightmare. Any ideas?

+2


source to share


2 answers


You can create these objects and just not insert them into the context:

NSEntityDescription *entity = [NSEntityDescription entityForName:entityName
                                          inManagedObjectContext:managedContext];
ManagedObjectClass *volatileObject = [[ManagedObjectClass alloc] initWithEntity:entity
                                                 insertIntoManagedObjectContext:nil];

      

And if you want to keep it, you just paste it into the context:



[managedContext insertObject:volatileObject];

      

(if you forget to add it it will give you a dangling object error when trying to store it in context)

+2


source


Create a new one NSManagedObjectContext

with in-memory storage. Then you can put your transition objects in this context and they won't persist.

NSManagedObjectModel *mom = [NSManagedObjectModel mergedModelFromBundles:[NSArray arrayWithObject:[NSBundle mainBundle]]]; // though you can create a model on the fly (i.e. in code)
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc]     initWithManagedObjectModel:mom];

NSError *err;

// add an in-memory store. At least one persistent store is required
if([psc addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:&err] == nil) {
  NSLog(@"%@",err);
}

NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
[moc setPersistentStoreCoordinator:psc];

      



If you want to keep them, just move them to the proper store later, or merge the context.

Otherwise, if you finally put them in the context of anyway (ie, you just do not want them to appear in the list until they have been saved), just set setIncludesPendingChanges

in NO

in its NSFetchRequest

.

+1


source







All Articles