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 bestrong
. Outlets that you create should therefore typically beweak
, 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
’sview
outlet, orNSWindowController
’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
除了选中的答案之外,其他人的回答也非常有意思,大家可以看看。