The right way to achieve this kind of thing is the new context of the managed entity. You create a managed object context with the same persistent storage:
NSManagedObjectContext *tempContext = [[[NSManagedObjectContext alloc] init] autorelease]; [tempContext setPersistentStore:[originalContext persistentStore]];
Then you add new objects, mutate them, etc.
When the time comes to save, you need to call [tempContext save: ...] in tempContext and process the save notification to merge this into the original context. To drop objects, just release this temporary context and forget about it.
Therefore, when you save the temporary context, the changes are saved in the repository, and you just need to return these changes to your main context:
- (void)tempContextSaved:(NSNotification *)notification { [originalContext mergeChangesFromContextDidSaveNotification:notification]; }
It is also a way to handle multi-threaded operations with master data. One context for the thread.
If you need access to existing objects from this temporary context (to add relationships, etc.), you need to use the object identifier to get a new instance, for example:
NSManagedObject *objectInOriginalContext = ...; NSManagedObject *objectInTemporaryContext = [tempContext objectWithID:[objectInOriginalContext objectID]];
If you try to use NSManagedObject in the wrong context, you will get exceptions when saving.
Mike Weller Jul 15 '10 at 14:37 2010-07-15 14:37
source share