Why does Xcode create a weak reference for an IBOutlet? [duplicate]

人盡茶涼 提交于 2019-12-10 12:14:23

问题


I notice when i create a outlet within a story board it generates the following code __weak IBOutlet UILabel *mLabel;.

Why is it declaring it as a weak pointer? From my understanding, when the object gets released, all its members will get released too. In most of my code I'm declaring the outlets as strong pointers. Is this going to create problems?


回答1:


According to iOS Developer Library: link here

Section: Managing the Lifetimes of Objects from Nib Files

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’s window outlet).

@property (weak) IBOutlet MyView *viewContainerSubview;

@property (strong) IBOutlet MyOtherClass *topLevelObject;




回答2:


To expand upon @Joel's answer, this is not a change between ARC and manual reference counting (MRC). In MRC code with a NIB, only your root-level view is declared as:

@property (nonatomic, retain) IBOutlet UIView *view;

All subviews of self.view should be declared as:

@property (nonatomic, assign) IBOutlet UIView *aSubView;

When this is converted to ARC, it should be like this:

@property (nonatomic, strong) IBOutlet UIView *view;
@property (nonatomic, weak) IBOutlet UIView *aSubView;

The reason for this is to save work (and complexity) in your -viewDidUnload method. When your root-level views are released, all subviews will be automatically released. If you a strong reference, the subview will not be deallocated unless your -viewDidUnload explicitly contains:

self.aSubView = nil;

Anyone reading this far will note that -viewDidUnload is depreciated as of iOS 6.0. That renders much of this irrelevant, but it's still good practice to follow the conventions.




回答3:


You'll only need to have a strong reference to the root level objects of the UI, anything below this can be weak (as the parent objects will own their children).

My recommendation for a better understanding. Apple Docs.

Transitioning To ARC



来源:https://stackoverflow.com/questions/21654113/why-does-xcode-create-a-weak-reference-for-an-iboutlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!