Search code examples
core-datansmanagedobjectcontext

NSManagedObjectContextObjectsDidChangeNotification deleted objects issue


It appears as though I've exposed a strange issue where my deleted objects are not actually deleted. This only occurs when I'm responding to theNSManagedObjectContextObjectsDidChangeNotification.

More specifically: I have a list of A <->>B. A cascade deletes 'owned' instances of B.
When I delete an instance of A, it's 'owned' B instances are deleted, but the A instance is not deleted.

When I invoke [context processPendingChanges]; at the top of my notification handler, the issue seems to only occur when I delete the last object. Otherwise, instances of A tend to stick around.

So, it seems that the root of the issue is in something I don't understand about Core Data. Figuring out why has been unproductive. Can anyone list the reason(s) I might see this behavior?


Solution

  • I found two reasons this can happen:

    A) In my case my first strategy was to build temporary graphs of the deleted managed objects as an organizational convenience. You must modify deleted objects in a temporary managed object context, or else any changes you make to the deleted objects supersede the deletion. Reset the temporary context as soon as you're done operating on the (stale) deleted managed objects.
    B) The objects must have a reference count of 0 when deleted. This means they have to be released from all fetched results controllers, NSArrays, etc. prior to deletion.

    Satisfying A and B solved this issue.