如何避免嵌套对象导致的内存泄漏 [英] How to avoid memory leaks with nested objects

查看:80
本文介绍了如何避免嵌套对象导致的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一个Swift对象A,它引用了对象B和C,并且该对象B也引用了C,如下所示:

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

假设所有引用都很强,这会导致内存泄漏吗?为了避免泄漏,对象B对对象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?

谢谢!

推荐答案

在您的第一个示例中,只要B和C都没有强引用A,就不会有强引用周期,因此就不会出现内存问题(使用此方法至少是对象层次结构).同样,在您的第二个示例中,只要C没有对B的强引用,同样,也就没有强参考周期.

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.

这篇关于如何避免嵌套对象导致的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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