How does UIView prevent retain cycle?

2019-05-18 10:04发布

问题:

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.