How does UIView prevent retain cycle?

我与影子孤独终老i 提交于 2019-12-10 10:38:52

问题


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

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


回答1:


UIView's superview property is declared as

@property(nonatomic, readonly) UIView *superview;

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 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.

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.

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



来源:https://stackoverflow.com/questions/29997800/how-does-uiview-prevent-retain-cycle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!