简体   繁体   English

iOS:简单的保留周期

[英]iOS: Simple Retain Cycle

Let's say you have have a viewController with: 假设您有一个带有以下内容的viewController:

@property (strong) object* A 
@property (strong) object* B

You then purposely create a retain cycle at somepoint, without timers, such that 然后,您有目的地在没有计时器的情况下有目的地创建一个保留周期,这样

self.A.someStrongProperty = self  //retain cycle

Question: Suppose the VC containing these properties gets deallocated, could a retain cycle or memory leak persist? 问题:假设包含这些属性的VC被释放,保留周期或内存泄漏是否会持续?

In the code you have posted above, there is no retain cycle. 在上面发布的代码中,没有保留周期。

A retain cycle would be self.A = self; 保留周期为self.A = self; or more likely, self.A.someStrongProperty = self . 或更可能是self.A.someStrongProperty = self

Edit: In the case you have edited above, assuming self is a view controller, it would not deallocate because of the retain cycle. 编辑:如果您在上面进行了编辑,则假设self是一个视图控制器,由于保留周期,它不会取消分配。 You should change your someStrongProperty to be a weak property, which will prevent the retain cycle. 您应该将someStrongProperty更改为weak属性,这将阻止保留周期。

Yes in case you retain self you are causing a retain cycle. 是的,如果您保留self ,则会导致一个保留周期。

This will cause the self instance not to be deallocated, causing a memory leak. 这将导致self实例不被释放,从而导致内存泄漏。

To prevent this, you can either use a weak property or manually setting someStrongProperty to nil at some point, in order to break the retain cycle. 为了防止这种情况,您可以使用weak属性或在某个时候手动将someStrongProperty设置为nil ,以打破保留周期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM