如何判断“NSManagedObject"是否已被删除? [英] How can I tell whether an `NSManagedObject` has been deleted?

查看:24
本文介绍了如何判断“NSManagedObject"是否已被删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSManagedObject 已被删除,并且包含该托管对象的上下文已被保存.我知道 isDeleted 返回 YES 如果 Core Data 将要求持久存储在下一次保存操作期间删除对象.但是,由于保存已经发生,isDeleted 返回 NO.

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

有什么好方法可以判断 NSManagedObject 是否在其包含上下文被保存后 被删除?

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

(如果你想知道为什么引用被删除的托管对象的对象还不知道删除,那是因为删除和上下文保存是由后台线程启动的,该线程使用 performSelectorOnMainThread:withObject:waitUntilDone:.)

(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 performSelectorOnMainThread:withObject:waitUntilDone:.)

推荐答案

检查托管对象的上下文似乎有效:

Checking the context of the managed object seems to work:

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

来自 Apple 关于 managedObjectContext 的文档...

From Apple's documentation on managedObjectContext ...

这个方法可能返回 nil 如果接收者已从其删除上下文.

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.

这两个似乎都是好事.

更新:如果您要测试专门使用 objectWithID: 检索的托管对象是否已被删除,请查看 戴夫·加拉格尔的回答.他指出,如果您使用已删除对象的 ID 调用 objectWithID:,则返回的对象将是一个错误,没有有其 managedObjectContext 设置为零.因此,您不能简单地检查它的 managedObjectContext 来测试它是否已被删除.如果可以,请使用 existingObjectWithID:error:.如果不是,例如,您的目标是 Mac OS 10.5 或 iOS 2.0,则需要执行其他操作来测试删除.请参阅他的回答详情.

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.

这篇关于如何判断“NSManagedObject"是否已被删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆