I have 2 NSManagedObject contexts, one temporary and another that is primary. The temporary context has its parent context set to the primary context. I use them both in the following cases:
- When I create a "new" object, I create a new one with the temporary context. If the user hits "cancel" and decides not to create the new object, I simply delete the object from the managed object context and save that context.
- If the user saves this new object, I save the temporary context and then save the primary context to persist these changes. I use the "performBlock" methods and chain the saves, as is recommended by Apple and other Stackoverflow posts.
- If I'm editing an existing object, I keep it in the primary context during edits. If the user hits "cancel," I call "rollback" on the primary context, which discards all of the changes.
In these cases, everything seems to work fine. After the saves, the temporary context reports that it has 0 registered objects, and the primary context has an additional object.
However, there is a case where creating a "new" object includes another object which has a relationship to this new object. So for this object, I create the new object, create the "child" object, and set it on the parent. So there are 2 NSManagedObjects. I perform a "save" the same way - the temporary context is saved, and then the primary is saved afterward. The problem is that my temporary context is still stating that it has 2 registered objects after the save is completed. The primary object also states that it has 2, and they are all displaying correctly.
I can fix this by performing a "reset" on the temporary context after performing the "save" on the temporary context. However, this just doesn't seem right. Why should I have to do that? Why is my temporary context still reporting registered objects even after performing a save?
EDIT: I can also fix this by performing "refreshObject:object mergeChanges:NO" on the object from the temporary context after performing the save on the temporary context. This seems like the best solution for now (until someone can explain why I need to do this or why this is happening). My guess is that the objects are referring to each other, which is causing the objects to not release.