How can I tell whether an `NSManagedObject` has been deleted?

Checking the context of the managed object seems to work:

if (managedObject.managedObjectContext == nil) {
    // Assume that the managed object has been deleted.
}

From Apple’s documentation on managedObjectContext

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

If the receiver is a fault, calling
this method does not cause it to fire.

Both of those seem to be good things.

UPDATE: If you’re trying to test whether a managed object retrieved specifically using objectWithID: has been deleted, check out Dave Gallagher’s answer. He points out that if you call objectWithID: using the ID of a deleted object, the object returned will be a fault that does not have its managedObjectContext set to nil. Consequently, you can’t simply check its managedObjectContext to test whether it has been deleted. Use existingObjectWithID:error: if you can. If not, e.g., you’re targeting Mac OS 10.5 or iOS 2.0, you’ll need to do something else to test for deletion. See his answer for details.

Leave a Comment