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

前端 未结 5 1567
[愿得一人]
[愿得一人] 2020-11-27 11:06

I have an NSManagedObject that has been deleted, and the context containing that managed object has been saved. I understand that isDeleted returns

5条回答
  •  醉话见心
    2020-11-27 11:40

    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.

提交回复
热议问题