ARC下IBOutlet用weak還是strong


原文來自這里

今天用Xcode5的時候,發現默認的IBoutlet的屬性設置為weak——因為Xcode5建立的工程都是ARC的了。但是當時還有點不明白,因為項目的原因,一直沒有正式使用過ARC。於是,為了搞清楚為什么,google了一下,有很多答案。試着從Apple文檔尋找線索,在這里找到了說明:

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 should therefore typically be weak, because:

  • Outlets that you create to subviews of a view controller’s view or a window controller’s window, for example, 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’swindow 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也沒有錯,“糾結誰對誰錯“的問題可能需要上升到模式或者編碼習慣的問題,已經超出本文的范圍。

最后附上stakoverflow上的答案:

http://stackoverflow.com/questions/7678469/should-iboutlets-be-strong-or-weak-under-arc/7729141#7729141

除了選中的答案之外,其他人的回答也非常有意思,大家可以看看。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM