您的位置:首页 > 移动开发 > IOS开发

IBOutlet对象应该使用strong还是weak修饰

2016-09-02 14:21 405 查看
ARC情况下,通常应该使用strong修饰,除非为了避免循环引用的情况。特别是在iOS6之后更应如此,使用weak修饰除了避免循环引用没有其他益处。

And the last option I want to point out is the storage type, which can either be strong
or weak. In general you should make your outlet strong, especially if you are connecting an outlet to a subview or to a constraint that's not always going to be retained by the view hierarchy. The only time you really need to make an outlet weak is if you
have a custom view that references something back up the view hierarchy and in general that's not recommended.

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).
@property (weak) IBOutlet MyView *viewContainerSubview;
@property (strong) IBOutlet MyOtherClass *topLevelObject;


While the documentation recommends using 
weak
 on
properties for subviews, since iOS 6 it seems to be fine to use 
strong
 (the
default ownership qualifier) instead. That's caused by the change in 
UIViewController
 that
views are not unloaded anymore.
Before iOS 6, if you kept strong links to subviews of the controller's view around, if the view controller's main view got unloaded, those would hold onto the subviews as long as
the view controller is around.
Since iOS 6, views are not unloaded anymore, but loaded once and then stick around as long as their controller is there. So strong properties won't matter. They also won't create strong reference
cycles, since they point down the strong reference graph.

That said, I am torn between using
@property (nonatomic, weak) IBOutlet UIButton *button;


and
@property (nonatomic) IBOutlet UIButton *button;


in iOS 6 and after:

Using 
weak
 clearly
states that the controller doesn't want ownership of the button.

But omitting 
weak
 doesn't
hurt in iOS 6 without view unloading, and is shorter. Some may point out that is also faster, but I have yet to encounter an app that is too slow because of 
weak
 
IBOutlet
s.

Not using 
weak
 may
be perceived as an error.

Bottom line: Since iOS 6 we can't get this wrong anymore as long as we don't use view unloading. Time to party. ;)

参考链接:


Should
IBOutlets be strong or weak under ARC?

为什么 iOS 开发中,控件一般为 weak 而不是 strong?

《招聘一个靠谱的 iOS》—参考答案(下)


IBOutlet连出来的视图属性为什么可以被设置成weak?

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息