swalkner
swalkner

Reputation: 17349

Core Data: is there a way to move/copy a NSManagedObect to another context?

I've got a NSManagedObject in Context A and would like to have it in Context B. If I use the objectID to load it in Context B, all the data in context A is lost, so I would like to copy/move the data, something like

[managedObjectInContextA copyTo:contextB];

How can I achieve this?

Thanks a lot,

Stefan

Upvotes: 0

Views: 696

Answers (2)

rgeorge
rgeorge

Reputation: 7327

Three steps:

  • early on, register somewhere appropriate for the NSManagedObjectContextDidSaveNotification. (The view controller that owns context B might be a good choice; it depends on your app architecture.)

  • Make changes to context A's copy of the object, and save context A. This causes the above notification to fire.

  • in the method that receives this notification, call mergeChangesFromContextDidSaveNotification: on context B. This causes context B to get in sync with the freshly saved changes.

Context B's copy of the object now has the new state.

If both copies of the object might have unsaved changes, things get more complicated. See NSManagedObjectContext's mergePolicy to see ways of handling that if you need to.

Upvotes: 1

Mundi
Mundi

Reputation: 80265

The most obvious solution would be to just save the data to the persistent store before switching contexts.

[managedObjectContextA save:&error];

Upvotes: 0

Related Questions