本文介绍了为什么 NSManagedObject 实例不持有对其 NSManagedObjectContext 的强引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如在关于 SO(以及 Apple docs),NSManagedObject 实例不具备强对它们起源的 NSManagedObjectContext 的引用.乍一看,这似乎是一个奇怪的决定,因为 NSManagedObject 实例在没有 context 的情况下几乎毫无用处,因为它会导致诸如 应该发生的故障没有触发.

As pointed out in another question on SO (and the Apple docs), NSManagedObject instances do not hold a strong reference to the NSManagedObjectContext from which they originated. On first blush, this seems like a strange decision, since NSManagedObject instances are nearly useless without their context, since it leads to confusing bugs such as faults not firing when they should.

谁能提供一些关于为什么会这样的背景?实现一个 NSManagedObject 子类是否会自动持有对其 NSManagedObjectContext 的强引用?

Can anyone provide some background on why this is the case? Would it be dangerous to implement an NSManagedObject subclass that automatically holds a strong reference to its NSManagedObjectContext?

感谢对这个问题的出色回答,我发现我的托管对象是针对 RestKit 有意临时的 NSManagedObjectContext 创建的.这是我的下一个问题,特定于 RestKit,此处.

thanks to great answers to this question, I've discovered that my managed objects were created against an intentionally temporary NSManagedObjectContext by RestKit. This follows into my next question, specific to RestKit, here.

推荐答案

NSManagedObjectContext 拥有它的 NSManagedObject 比其他方式更有意义.

It makes more sense for an NSManagedObjectContext to own its NSManagedObjects than the other way around.

请记住,上下文就像一个画板,上面有它的所有对象.如果该上下文消失,则对象不再有效.如果对象拥有上下文,那么消失的上下文不会对对象做任何事情,并且它们看起来仍然有效.换句话说:上下文可以没有对象而存在,对象不能没有上下文而存在.

Keep in mind that the context is like a draw pad with all its objects on it. If that context goes away, the objects are no longer valid. If the objects owned the context, then the context going away would do nothing to the objects and they still appeared to be valid. In other words: a context can exist without objects, objects can't exist without a context.

当然,混合模型(其中一个上下文拥有它的对象,而对象拥有它们的上下文)也不起作用,因为那样你会遇到一个保留循环.

Of course, a hybrid model (where a context owns its objects and objects own their context) wouldn't work either, because then you would run into a retain cycle.

NSManagedObject 实例在没有上下文的情况下几乎毫无用处

它们可以(虽然不一定),但请记住,它们确实引用了它们的上下文!大概这是一个弱引用,但仍然是一个引用.如果该引用返回 nil,则对象无效.如果您确保您的上下文保持不变(这就是我在另一个问题的回答中所做的),您就不会遇到任何问题.

They can be (though not necessarily), but remember that they do have a reference to their context! Presumably it's a weak reference, but a reference nonetheless. If that reference returns nil, the object is invalid. If you make sure your context stays around (which is what I did in my answer to the other question), you won't have any issues.

这篇关于为什么 NSManagedObject 实例不持有对其 NSManagedObjectContext 的强引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:20