在 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/