How do I copy or move an NSManagedObject from one context to another?
First, having more than one NSManagedObjectContext
on a single thread is not a standard configuration. 99% of the time you only need one context and that will solve this situation for you.
Why do you feel you need more than one NSManagedObjectContext
?
Update
That is actually one of the few use cases that I have seen where that makes sense. To do this, you need to do a recursive copy of the object from one context to the other. The workflow would be as follows:
- Create new object in persistent context
- get a dictionary of the attributes from the source object (use
-dictionaryWithValuesForKeys
and-[NSEntityDescription attributesByName]
to do this. - set the dictionary of values onto the target object (using
-setValuesForKeysWithDictionary
) - If you have relationships, you will need to do this copy recursively and walk the relationships either hard coded (to avoid some circular logic) or by using the
-[NSEntityDescription relationshipsByName]
As mentioned by another, you can download the sample code from my book from The Pragmatic Programmers Core Data Book and see one solution to this problem. Of course in the book I discuss it more in depth :)
The documentation is misleading and incomplete. The objectID methods do not themselves copy objects they simply guarantee that you've gotten the specific object you wanted.
The context2
in the example is in fact the source context and not the destination. You're getting a nil because the destination context has no object with that ID.
Copying managed objects is fairly involved owing to the complexity of the object graph and the way that the context manage the graph. You do have to recreate the copied object in detail in the new context.
Here is some example code that I snipped from the example code for The Pragmatic Programmer's Core Data: Apple's API for Persisting Data on Mac OS X. (You might be able to download the entire project code without buying the book at the Pragmatic site.) It should provide you with a rough idea of how to go about copying an object between context.
You can create some base code that copies objects but the particulars of each object graph's relationships usually mean that you have to customize for each data model.