Transferring objects between contexts of a managed object

I have an iphone application with 2 managed object contexts. One of my contexts is dedicated to the collector, which allows the user to add new entries and then select one of these new entries. When the collector is hidden, this managed entity context is saved and discarded.

Then I want to use this selected object in my second context of managed objects and add (link) it to another object. These changes can be saved or deleted. That's why the first MOC was created so that changes made in the collector are always saved no matter how they save or discard the changes in the second MOC.

Hope this is clear! My problem is that when the user selects an object from the collector, this object is in a different context where it should be used. Is there a way to pass objects between contexts? Perhaps using the identifier of the object (after saving it).

Thanks for your help!

+3
source share
1 answer

You mentioned the correct solution in the question. You cannot pass NSManagedObjects between multiple contexts, but you can pass NSManagedObjectID and use them to request the appropriate context for the object represented by this identifier. So just save the data (using save :), and then pass the ID to another context and use it to ask the context for the corresponding object.

Depending on what you want to do, you may want to build mergeChangesFromContextDidSaveNotification: so that changes in one context are automatically reflected in another.

+5
source

Source: https://habr.com/ru/post/1303663/


All Articles