Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
137 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...