为什么doen't NSManagedObject实例持有对他们的NSManagedObjectContext的强引用? [英] Why doen't NSManagedObject instances hold a strong reference to their NSManagedObjectContext?

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

问题描述

正如 SO中的另一个问题(以及 Apple docs ), NSManagedObject 不会强烈引用它们源自的 NSManagedObjectContext 。在第一次刷新时,这看起来像一个奇怪的决定,因为 NSManagedObject 实例没有他们的上下文几乎没用,引起混乱的错误,例如当他们应该触发故障时



任何人都可以提供一些背景为什么是这样的情况?实现一个 NSManagedObject 子类会自动保存对它的 NSManagedObjectContext



编辑:感谢这个问题的很好的答案,我发现我的托管对象是针对有意临时 NSManagedObjectContext 由RestKit。以下是我的下一个问题,特定于RestKit,此处

NSManagedObjectContext 拥有其 NSManagedObject s更有意义



请记住,上下文就像一个绘图板及其所有对象。如果上下文消失,对象不再有效。如果对象拥有上下文,那么离开的上下文对对象不起作用,并且它们似乎仍然有效。换句话说:一个上下文可以没有对象,对象不能没有上下文。



当然,一个混合模型(上下文拥有对象和对象自己的上下文)也不会工作,因为那样会遇到一个保留周期。


NSManagedObject实例没有上下文


它们可以是(但不一定),但是请记住,他们确实有对它们的上下文的引用!大概是一个弱的参考,但是一个参考。如果该引用返回nil,则对象无效。如果你确保你的上下文保持不变(这是我在回答另一个问题时做的),你就不会有任何问题。


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.

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?

Edit: 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.

解决方案

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 instances are nearly useless without their context

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.

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

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