UIView如何防止保留周期? [英] How does UIView prevent retain cycle?

查看:84
本文介绍了UIView如何防止保留周期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

子视图引用了超级视图,而超级视图也引用了(子视图)子视图.

Subview has a reference to superview, while superview also has reference (subviews) to subview.

我想知道为什么这不会导致保留周期?

I'm wondering why this doesn't cause retain cycle?

推荐答案

UIViewsuperview属性声明为

@property(nonatomic, readonly) UIView *superview;

在Objective-C中,自引入ARC以来,默认情况下声明为没有不同所有权说明符的属性默认为assign strong,但是,UIKit标头似乎未使用ARC,因此此属性最类似于assign.还要注意,由于该属性是只读的,因此源中很可能有一个自定义的getter,因此该属性中的所有权说明符不一定告诉我们任何信息.可以肯定地说,苹果公司以避免保留周期的方式实施了它.

In Objective-C, properties declared without a different ownership specifier are assign by default strong by default as of the introduction of ARC, however, the UIKit headers appear to not be using ARC, so this property is most like assign. Note also, since the property is readonly, there is most likely a custom getter in the source, so the ownership specifier in the property doesn't necessarily tell us anything. It's safe to assume that Apple has implemented it in such a way as to avoid retain cycles.

assign等效于__unsafe_unretained,这是一个非归零弱引用.这意味着它不会保留对象,但是在释放对象时不会将其设置为nil.它具有比weak更高的性能(因为不需要对其进行检查和清零),但不安全,因为如果释放引用的对象,则可能会访问垃圾内存.

assign is equivalent to __unsafe_unretained, which is a non-zeroing weak reference. This means that it does not retain the object, but will not be set to nil when the object is deallocated. This has higher performance than weak (since it doesn't need to be checked and zeroed), but unsafe, since you could be accessing garbage memory if the referenced object is deallocated.

还要注意,该属性被声明为readonly,这意味着它实际上可以实现为返回私有实例变量的方法,或者完全执行我们不知道的其他事情.基本上,最重要的是,您可以假定此属性不保留其引用的对象.

Also note, the property is declared as readonly, which means it could actually be implemented as a method that returns a private instance variable, or does something else entirely that we don't know about. Basically, all that matters is that you can assume that this property does not retain the object it refers to.

在今天的新代码中,您应该使用weak而不是assign.

In new code today, you should be using weak instead of assign.

这篇关于UIView如何防止保留周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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