What is better between "weak" and "strong" for IBOutlet variables?

What is better between "weak" and "strong" for IBOutlet variables? :-)

Answered by macnib in 155015022

If the outlet is referencing a ui object in the view heirarchy then I would make it weak. The view heirarchy already has a strong reference. Might help avoid reference cycles when your dismissing the view controller.

As of 2015, recommended best practice from Apple was for IBOutlets to be strong unless weak is specifically needed to avoid a retain cycle.


See:

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/LoadingResources/CocoaNibs/CocoaNibs.html#//apple_ref/doc/uid/10000051i-CH4-SW6

Better for what?


If the view is being added and removed from a parent view, strong is the only way to maintain a reference to the view. If the view is always a child of another view, weak is the way to go.

Accepted Answer

If the outlet is referencing a ui object in the view heirarchy then I would make it weak. The view heirarchy already has a strong reference. Might help avoid reference cycles when your dismissing the view controller.

As per Apple's 2015 guidelines, you're safer making all of your IBOutlets strong instead of weak, with the exception of custom views which may have references to views upstream in the view hierarchy (which is a bad idea in the first place). If you make an IBOutlet weak, then you should be prepared that if you remove that object from the view hierarchy your reference to it will be nil.


Basically you should know what you're doing and each situation needs to be handled on a case by case basis.

Thanks,


Neal

What is better between "weak" and "strong" for IBOutlet variables?
 
 
Q