Does an NSManagedObject retain its NSManagedObjectContext?

旧街凉风 提交于 2019-12-05 16:58:23

NSManagedObject DOES NOT hold strong reference to its NSManagedObjectContext. I've checked that on a test project. Therefore, you should keep strong reference to NSManagedObjectContext as long as you use its objects.

Wow, over two years old and no accepted answer here :)

When I wrote that post I did indeed mean it keeps a reference to its associated NSManagedObjectContext. If a NSManagedObject retained the NSManagedObjectContext then it would most likely run into problems.

In either case, whether the MOC is retained by the MO is irrelevant to your application design. If you need the MOC to stay around then you need to retain it (now referred to as a strong reference) or it will go away. What the frameworks do internally is not our problem. We just need to make sure we balance our retains and releases.

Matt,

I think Marcus may have miswrote that a NSManagedObject retains its context. Every NSManagedObject maintains a link to the context. Unless individual objects have an internal retain cycle or are retained outside of their context, then, in my experience, they are all released when the context is released. If they retained the context, then this would almost certainly not be the case.

The above said, you can easily write code to test Marcus' claim. Override -dealloc and log when it is called.

IMO, it is a best practice to retain your context until you are done with it. Depending on an undocumented behavior is probably not wise.

Andrew

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!