Just got a new MBPro which means a fresh install of Xcode. When using storyboards and (control) dragging to create outlets in the assistant, it now defaults to weak var
. A while back, this was the default. But then at some point, it seemed to switch to not weak.
Why does the default change, and what is the better default for outlet variables bound to buttons and things?
As holex said. It depends on your usecase. There is no best practise. And there are historical grown options to deal with views.
First and foremost:
If a view is added to a view hierarchy (eg. addSubview()) it will have a strong relationship.
Thats fine, unless you want to work with the added view. To do that you need a reference.
One variant would be traverse the array of subviews and look for your view. Back in time for more simple UIs this would be sufficient and thats why its build in. Each view can have a tag and the superview of your view can locate that one.
func viewWithTag(_ tag: Int) -> UIView?
Another way would be holding a reference to the view instead of looking it up. Thats the point where outlets come into play. However, if you hold a reference to an object you create by default a strong relationship. That means there are two places where the object is kept alive.
Back the time was this fine. Apps where more simpler and if a view got stuck, it was no biggy as the garbage collector discards all objects when the app gets disposed. (Ok, that is absolutely not a good practise)
If you have a more static UI, let's say you are experimenting, it doesn't really matter. Having a weak relationship is ok.
Btw Xcode ask you if you want a strong or weak reference and uses your decision as default. Possible you changed it once and got used to the new "default"
If you have a more dynamic UI, then have a look how UITableView works. UITableViewCells are views and you usually don't hold references to them to modify them.
But the best recommendation for Outlets is: Ask your self if you really need it. Often should code that modifies a UIView in some way be with the views own class, instead of keeping all code in one place. (MVC doesn't mean all code goes into the UIViewController)