Use Weak property to declare Outlet
When we use interface builder to generate an outlet object, it is generally used as a subview. For example, view of uiviewcontroller. Therefore, the owner of outlet is a superview object, which has a parent-child relationship. From the last iPhone Development
(4)-we know from the arc cycle that when there is a "Parent-Child" Relationship between objects, we need to use weak references to avoid "circular references ".
Viewcontroller itself is not the owner of outlet, so weak property declaration is used.
Simplify viewdidunload
When both outlet use the weak property declaration, another benefit is to simplify the processing of viewdidunload.
When the system memory of IOS is insufficient, uiviewcontroller will unload all views that are not displayed, that is, call the viewdidunload interface.
Therefore, in case of strong reference, the ownership needs to be released,
@ Property (nonatomic, strong) iboutletUilabel*Label;
( Void ) Viewdidunload {Self . Label = Nil ; // Clear strong references and release ownership [Super Viewdidunload];} |
Without the processing of self. Label = nil, uiviewcontroller will not release the ownership of the label. As a result, the system calls unload, but the subview object remains in the memory. As the number of controls on the Interface increases, memory leakage will increase.
What will happen if weak property declaration is used?
@ property (nonatomic, weak) iboutlet uilabel * label ; |
At this time, when the system is unload, because the label is not strongly referenced, more arc rules, then the label object is released. At the same time of release, the variable automatically points to nil.
-( Void ) Viewdidunload {// Nothing to worry about here [ Super Viewdidunload];} |
In fact, if our viewdidunload is only used to release the outlet, this function can also be reloaded.
When to use strong property
We can also see that not all outlet statements are correct with weak references. When the first layer of view or
If Windows is used as an outlet, it cannot be declared as a weak reference property. (For example, each scene of the storyboard)
The reason is simple. objects that are not strongly referenced by anyone will be released immediately after they are generated.
In summary, when using outlet, we should pay attention to different situations to use strong or weak.
Blogger: Yi Feifei
Link: http://www.yifeiyang.net/development-of-the-iphone-simply-5/
Reprinted text.