This question already has an answer here:
-
Should IBOutlets be strong or weak under ARC?
11 answers
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?
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;
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.
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