ios - 上下文检测冲突对象

标签 ios core-data nsmanagedobjectcontext

在 iOS Core Data 中,有一个关于 NSManagedObjectContext 的方法 detectConflictsForObject:

此方法的文档说:

If on the next invocation of save: object has been modified in its persistent store, the save fails. This allows optimistic locking for unchanged objects. Conflict detection is always performed on changed or deleted objects.

我有一个[context save],无论我是否使用detectConflictsForObject,它都会引发异常。

我认为此方法将帮助我确定对[context save]的调用是否会导致崩溃。

我的具体情况是这样的。 我有上下文 A 是 B 的父上下文。B 是 C 的父上下文。

一些NSManagedObject已从B中删除,一段时间后[C save]即将被调用。这会导致“无法完成故障”异常,我认为我可以使用detectConflictsForObject方法尽早检测到该异常,从而避免崩溃。

最佳答案

此问题在本文档 "Troubleshooting Core Data" 中有描述。我认为您尝试从先前在其他上下文中删除的对象中检索属性或关系。要检查对象的现有状态,您可以使用 existingObjectWithID:error: NSManagedObjectContext 的方法。如果该对象无法获取、或者不存在、或者不能出错,则返回 nil。例如:

- (void)doSomethingWithAttributesOfObject:(NSManagedObject *)object {
    if ([self.managedObjectContext existingObjectWithID:object.objectID error:nil])
        ; // you can do something with object
    else
        ; // object was deleted
}

关于ios - 上下文检测冲突对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29649371/

相关文章:

ios - 将 SQLite 导入 CoreData

ios - CoreData 无法解决未修改对象发生的错误。

ios - 以编程方式设置核心数据 - NSManagedObjectContext 从何而来?

iOS:DequeTableViewCell..有点困惑

android - Admob 为 Android 和 IOS 使用相同的 Interstitial 和 BannerID

ios - swift : Terminating app due to uncaught exception 'NSInvalidArgumentException' , 原因: 'Entity name must not be nil.'

iphone - 单例 managedObjectContext

ios - 缺少 ios 分发签名身份未过期的证书

ios - 如何存储数据以备将来在 iOS 应用程序中使用

ipad - [ Controller WillChangeContent :]: message sent to deallocated instance