[英]Orphaned objects in iOS CoreData
假设我有一个称为Player
的CoreData实体类型,并且它与一个名为PlayerPurpose
的实体类型具有一对一的关系( purpose
)。 为了完整PlayerPurpose
,假设我们在PlayerPurpose
有一个相反的关系,称为parentPlayer
。 考虑以下快速代码:
// Assume we already have a player object in a NSManagedObjectContext called context:
player.purpose = NSEntityDescription.insertNewObjectForEntityForName("PlayerPurpose",
inManagedObjectContext: context) as PlayerPurpose;
// Later in the code, we set the value to nil (or we could have replaced
// it with another call to insertNewObjectForEntityForName)
player.purpose = nil;
// What happens to the previous playerPurpose object within the Managed Object Context?
我的问题:如果托管对象上下文中的原始playerPurpose对象在数据中的唯一引用设置为nil(或替换为另一个对象),将会发生什么?
这与关系删除规则并没有真正的关系,因为我没有明确删除任何对象,而是将其从任何有意义的关系中删除,从而使其成为孤立对象。
从ARC的角度来看(如果PlayerPurpose只是一个普通的非托管对象),原始的PlayerPurpose实例现在没有引用,因此可以从内存中清除它-但是在托管对象上下文中会发生什么? CoreData是否将其识别为孤立对象并通过上下文将其删除?
如果不是这样,那么我假设如果要摆脱对它的所有引用,我必须小心删除通过上下文创建的任何托管对象。 假设是这种情况,是否可以使用一种好的模式来确保从NSManagedObjectContext中清除孤立对象,并且不再将它们存储在持久性存储中?
谢谢!
在这种情况下,Core Data不会自动删除对象,因为“孤立”是您的代码具有的概念,而Core Data不能识别该概念。 没有理由仅因为其关系之一为nil来删除PlayerPurpose
对象。
确保删除PlayerPurpose
实例的最可靠方法是
NSManagedObject
子类(如果您还没有的话)。 purpose
的Player
子类。 如果新值是nil,则删除旧值。 您也可以通过确保在适当的时间调用deleteObject:
来处理此问题。 或者,您可以运行清理步骤,在该步骤中,为parentPlayer
获取每个PlayerPurpose
nil的parentPlayer
并删除它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.