首先有一點,在OC中,如果對象沒有強引用,就會被自動釋放,那么為什么控件還可以設為weak?
1. 從storyboard或者xib上創建控件,在控件放在view上的時候,已經形成了如下的引用關系,以UIButton為例:
UIViewController->UIView->subView->UIButton
然后你為這個UIButton聲明一個weak屬性
@property(nonatomic,weak) IBOOutlet UIButton *btn;
相當于xib/sb對這個Button是強引用,你聲明的屬性對它是弱引用。
2.手動創建控件
a). 將控件聲明成strong
@property(nonatomic,strong) UIButton *btn;
那么你在實現這個控件時只需這樣:
_btn = [[UIButton alloc]init];
[self.view addSubview:_btn]
b). 將控件聲明成weak
@property(nonatomic,weak) UIButton *btn;
那么你在實現這個控件時需要這樣:
UIButton *button = [[UIButton alloc]init];
_btn = button;
[self.view addSubview:_btn];
============================
最近看的黑馬iOS視頻上給的建議的是:
1.如果用Stroyboard拖線,用weak
2.如果自定對象,用strong(但我還是習慣用weak暫時=_=)
其實不管聲明的屬性是強引用還是弱引用,在控制器消失的時候,這個屬性消失,View消失,subViews消失,控件也就消失了。
=============================
之前專門搜過相關的問題,貼上來:
IBOutlet的屬性一般可以設為weak是因為它已經被view引用了,除非view被釋放,否則IBOutlet的屬性也不會被釋放,另外IBOutlet屬性的生命周期和view應該是一致的,所以IBOutlet屬性一般設為weak。
可參考如下:
From a practical perspective, in iOS and OS X outlets should be defined as declared properties. Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong. Outlets that you create will therefore typically be weak by default, because:
Outlets that you create to, for example, subviews of a view controller’s view or a window controller’s window, are arbitrary references between objects that do not imply ownership.
The strong outlets are frequently specified by framework classes (for example, UIViewController’s view outlet, or NSWindowController’s window outlet).
簡單的說,如果IBOutlet對象是nib/sb scene的擁有者(File’s owner)所持有的對象,那么很顯然擁有者必須“擁有”對象的指針,因此屬性應設置為strong。而其他的IBOutlet對象的屬性需要設置為weak,因為擁有者并不需要“擁有”他們的指針。舉例來說,UIViewController的view屬性是strong,因為controller要直接擁有view。而添加到view上的subviews,作為IBOutlet只需要設置為weak就可以了,因為他們不是controller直接擁有的。直接擁有subviews的是controller的view,ARC會幫助管理內存。
緊接著,文檔里又提到:
Outlets should be changed to strong when the outlet should be considered to own the referenced object:
As indicated previously, this is often the case with File’s Owner—top level objects in a nib file are frequently considered to be owned by the File’s Owner.
You may in some situations need an object from a nib file to exist outside of its original container. For example, you might have an outlet for a view that can be temporarily removed from its initial view hierarchy and must therefore be maintained independently.
第一種情形前面已經解釋過了,對于第二種,通俗點將,就是controller需要直接控制某一個subview并且將subview添加到其他的view tree上去。
單純從ARC的角度思考,用weak也是很顯然的:因為subview添加到view上時,view會“擁有”subview。當然,給IBOutlet屬性設置為strong也沒有錯,“糾結誰對誰錯“的問題可能需要上升到模式或者編碼習慣的問題,已經超出本文的范圍。