Weak, unowned or robust subviews?
I’ve acquired numerous emails and tweets about this subject, so I made a decision to write down about it, as a result of it’s actually exhausting to discover a correct reply for this query on the web. There are some nice posts and programming guides, some some articles are a bit older, nonetheless many individuals are asking the weak vs robust IBOutlet query even on the official boards, however noone actually explains the explanations, even on the boards they solely suggest this WWDC session video. So what is going on on right here? 🤔
I did a little analysis on the subject and the very very first thing that we should always state is that this: Apple eliminated the viewDidUnload technique in iOS6 and from that model the iOS view controller lifecycle modified a bit. If you do not know a lot in regards to the lifecycle strategies (demystified), it’s best to learn this text. This was fairly an enormous change and Apple additionally touched their inside view administration. Earlier than iOS6 it was a standard observe to outline weak subviews. As a result of that they had a powerful reference to it and so they weren’t releasing it until you eliminated it from the view hierarchy.
This was about 10 years in the past. Now why are we nonetheless afraid of robust subviews? The primary cause was the addSubview technique. The documentation states that it will create a powerful reference, which routinely triggered my mind and I outlined my views as weak pointers, since they are going have a powerful reference to their dad and mom. Appears affordable, proper? ðŸ§
Weak subviews
Properly, the issue is that if you wish to outline a weak variable we have now to make use of an non-compulsory, however I do not like the thought of utilizing an non-compulsory variable for the reason that view goes to be at all times there, it is a part of the view hierarchy in some unspecified time in the future in, it isn’t going anyplace. It is solely going to be “destroyed” when my view controller is deallocated. Ought to I declare it as an implicitly unwrapped non-compulsory?!? Perhaps.
import UIKit
class ViewController: UIViewController {
weak var foo: UILabel!
weak var bar: UILabel?
override func viewDidLoad() {
tremendous.viewDidLoad()
foo.removeFromSuperview()
foo.textual content = "crash"
}
}
Truly you may go incorrect with unwrapped weak pointers, as a result of when you take away your view from the view hiearchy in some unspecified time in the future in time earlier than the view controller deallocation then your weak pointer will probably be nil
. On this case there will not be any extra robust references and your view will probably be deallocated straight away, so if it is an implicitly unwrapped non-compulsory, then we have now a hassle. Your app will crash when you attempt to entry the property, as a result of it will have a nil
worth.
So sure you should use implicitly unwrapped non-compulsory variables to retailer subviews, however solely if you’re positive that you’re not going to take away it from the hiearchy. This additionally signifies that you do not belief Apple’s view administration system, which is okay, there could be bugs, however actually that is fairly an important characteristic and it has been round for a decade by now. 🙃
The opposite different is to make use of an everyday weak non-compulsory variable, however in that case you may at all times should test if it is nil or not, which goes to be a ache within the ass, however at the least you are going to be secure for positive. Private opinion: it will not well worth the effort in any respect and I by no means saved views like this.
Robust subviews
My suggestion is to belief Apple and outline your subviews as robust properties. Okay, this can be problematic when you’ve got different robust references to the identical stuff, however basically if the view controller has the one reference to that given subview you ought to be completely effective.
Since it is a robust property you additionally should initialize the view, however that is not an enormous deal. You possibly can at all times initialize a view with a .zero
body and that is it. Alternatively you may create a subclass with an everyday init()
technique, that is even higher, becuase you will use auto structure for positive and this manner can set the translatesAutoresizingMaskIntoConstraints
property in a single go.
import UIKit
class Label: UILabel {
init() {
tremendous.init(body: .zero)
self.translatesAutoresizingMaskIntoConstraints = false
}
@out there(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been carried out")
}
deinit {
print("deinit Label")
}
}
class ViewController: UIViewController {
var foo: Label = .init()
var bar: UILabel = .init(body: .zero)
override func viewDidLoad() {
tremendous.viewDidLoad()
}
deinit {
print("deinit ViewController")
}
}
By implementing a customized deinit
technique and even higher, by making a symbolic breakpoint you may simply detect retain cycles and repair reminiscence points. I made some exams and I can affirm you do not have to be afraid of robust views, each the viewcontroller and the view goes to be deallocated if it is wanted. 👻
Unowned subviews
Unowned and weak are roughly equal, I would say that you simply will not have to outline views as unowned references, as a result of they are often problematic if it involves initialization. It is often higher to have a weak reference and test for nil
values, however in fact there could be some circumstances the place you would possibly want an unowned subview reference.
Utilizing loadView and viewDidLoad
The loadView technique can be utilized to create your individual views manually. You need to by no means name this technique immediately, nevertheless it’s save to override it. The opposite factor that you shouldn’t is that if you’re utilizing this technique to override the foundation view, you then should not name tremendous.loadView()
.
import UIKit
class ViewController: UIViewController {
override func loadView() {
view = UIView(body: .zero)
}
}
In each different case whenever you simply need to add views to the view hierarchy, it is utterly effective to name the tremendous technique. I am often implementing this technique to setup views and constraints.
import UIKit
class ViewController: UIViewController {
var foo: Label = .init()
override func loadView() {
tremendous.loadView()
view.addSubview(foo)
NSLayoutConstraint.activate([
view.centerXAnchor.constraint(equalTo: foo.centerXAnchor),
view.leadingAnchor.constraint(equalTo: foo.leadingAnchor),
view.trailingAnchor.constraint(equalTo: foo.trailingAnchor),
foo.heightAnchor.constraint(equalToConstant: 44),
])
}
}
This manner I can ensure that each single view is prepared by the point the viewDidLoad technique is known as. It’s doable to configure views contained in the loadView technique too, however I favor to maintain the hierarchy setup there and I place every little thing else contained in the viewDidLoad perform. I imply controller associated stuff solely, like establishing navigation bar buttons and issues like this.
As I discussed this in my earlier article, I favor to make use of subclasses to configure my views, I additionally transfer structure constraints there (as a perform that returns them primarily based on some parameters) to maintain the view controller clear. Contained in the viewDidLoad technique I can carry out further person interface associated actions, however that is it I do not use it for including or styling views anymore.