I have inherited code for an iPhone app using Core Data written by another team. In looking at the relationships between objects and how the objects are created/used in code I came to the realization that there was a memory leak into permanent storage. Sure enough when I delete all the top level objects out of Core Data there where objects left behind. Whats more there was an operation where the values/relationships of one object where copied to another and this left orphaned objects in Core Data.
I have since fixed the problems and there are no longer any new orphan objects being stored in Core Data. The problem now is how do I removed these orphan objects from the permanent storage of existing users that have been using the leaky app for who knows how long?
My initial thought was to copy the top level objects to another ManagedObjectContext. Then delete all the objects out of the original context. Finally copy the top level objects back into the original context. Does anyone see any problems with this or have a better idea?
Orphaned objects should have an empty relationship so you could just fetch on that empty relationship and delete the returned objects.
You probably want to update the data model to prevent orphaned objects. Orphans are usually a sign of a badly designed model. Make sure all relationships have a reciprocal and, when appropriate, make a relationship required. You can also add validation to prevent orphans.