Search code examples
objective-ccocoacore-datansmanagedobjectnsmanagedobjectcontext

When does NSManagedObject -managedObjectContext "return nil if the receiver has been deleted from its context"?


Apples documentation on NSManagedObject’s managedObjectContext method says:

This method may return nil if the receiver has been deleted from its context.

Does anyone know under what circumstances this method will return nil for a receiver that is deleted and under what circumstances it will still return the managed object context?

Background:
I override -didSave in order to move files that are referenced by a deleted managed object to the trash. After that, i have to clear the undo manager, because the deletion of this managed object can no longer be undone, as the files cannot be put back from the trash. So i will call:
[[[self managedObjectContext] undoManager] removeAllActions];
which will only work if -managedObjectContext does not return nil at this point.


Solution

  • Absolutely! There are a number of scenarios where this can happen. The most common is that the application is retaining a reference to the NSManagedObject after it was deleted from it's NSManagedObjectContext.

    The connection between an NSManagedObjectContext and an NSManagedObject is a weak one because of scenarios like this. The context observes and manages the life cycle of managed objects. The two are very much joined at the hip. When the object is deleted from the context, the next save will break that weak relationship between managed object and context. The deleted managed object's association with the managed object context is removed.