James Huddleston James Huddleston - 1 year ago 81
iOS Question

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

I have an

that has been deleted, and the context containing that managed object has been saved. I understand that
if Core Data will ask the persistent store to delete the object during the next save operation. However, since the save has already happened,

What is a good way to tell whether an
has been deleted after its containing context has been saved?

(In case you're wondering why the object referring to the deleted managed object isn't already aware of the deletion, it's because the deletion and context save was initiated by a background thread which performed the deletion and save using

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download