为什么NSManagedObject实例没有对其NSManagedObjectContext进行强引用? [英] Why doesn't NSManagedObject instances hold a strong reference to their NSManagedObjectContext?

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

问题描述

有关SO的另一个问题(以及故障不应该触发的时间.

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.

任何人都可以提供有关这种情况的背景信息吗?实施自动拥有对其NSManagedObjectContext的强引用的NSManagedObject子类是否会很危险?

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实例几乎是无用的

NSManagedObject instances are nearly useless without their context

它们可以是(尽管不一定),但是请记住,它们确实引用了上下文!大概这是一个较弱的参考,但是仍然是一个参考.如果该引用返回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进行强引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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