I want to be able to properly deep copy an object which is a NSManagedObject subclass.
A heavily simplified version of my data model is: 'parent' objects, each of which references (1 to many) several 'child' objects, each of which references (many to many) several 'label' objects. All objects are custom subclasses of NSManagedObject.
The catch is, the 'parent' object also references (1 to many) all the 'label' objects used by its 'child' objects, plus perhaps other 'labels' which may not be used by any 'child' (the idea being that this gives me an easy way to pull up a list of potential 'labels' for a user to add to a 'child'.)
No 'child' or 'label' objects are shared by more than one 'parent'.
So, each 'parent' has multiple 'children' and multiple 'labels', each 'child' has one 'parent' and multiple 'labels', each 'label' has one 'parent' and multiple 'children'.
I want to be able to deep copy 'parent' objects, maintaining the whole object tree, but I don't know how to resolve the loop of 'parent'>'child'>'label'>'parent'…etc.
If, while copying a 'parent', I copy all it's referenced 'child' objects first, and those 'child' objects copy their referenced 'labels' and also added them into that 'child's 'parent's 'labels' list, then how do I account for those 'labels' that should be in the 'parent's 'labels' list that are not referenced by any 'child'. If I union a copy of the original 'parent's 'labels' list into the new one, I end up with a list with 'labels' from the 'child' objects (do want), plus any loose 'labels' not associated with a 'child' (do want), plus copies of the 'labels' that were associated with the old 'parent's 'child' objects (do not want).
Conversely, if I copy the 'parent's referenced 'label' objects first, then they can't be linked to the 'child' objects they should be because the 'child' objects don't exist yet.
Aaaargh!
If this sounds at all confusing, that's because it is. At least, it's confusing me.