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

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

Accepted Reply

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.

Replies

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.

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