How to avoid memory leaks with nested objects

落花浮王杯 提交于 2019-12-25 18:26:23

问题


imagine a Swift object A that has a reference to objects B and C, and that object B also has a reference to C as depicted in below:

Object A:
- Object B
- Object C

Object B:
- Object C

Assuming that all the references are strong, will this cause a memory leak? Should the reference to Object C by Object B be a weak one in order to avoid leaks?

Thanks!


回答1:


In your first example, as long as neither B nor C have strong references back to A, there is no strong reference cycle and thus no memory problem (with this object hierarchy, at least). Likewise, in your second example, as long as C doesn’t have a strong reference back to B, again, no strong reference cycle.

The general idea in an object hierarchy is that a parent should have strong references to their children, but if the child needs any reference back up to its parent for any reason (and often, you don’t even need that), the child’s reference to the parent should be weak/unowned.

You just need to make sure that you don’t have circular cycle of strong references from the child back to the parent.



来源:https://stackoverflow.com/questions/48629539/how-to-avoid-memory-leaks-with-nested-objects

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