How to avoid memory leaks with nested objects

2019-09-20 16:28发布

问题:

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.