If my viewcontroller must be initialized with a delegate, is there any danger at all to doing using an unowned instead?
Using weak seems to introduce the probability of functions failing (see below), although it will not crash.
Would using unowned in this case be unsafe in anyway?
class MyViewController: UIViewController
private weak var delegate: MyViewControllerDelegate?
init(delegate: MyViewControllerDelegat) {
self.delegate = delegate
}
func foobar {
delegate??
}
compared to
class MyViewController: UIViewController
private unowned var delegate: MyViewControllerDelegate
init(delegate: MyViewControllerDelegate) {
self.delegate = delegate
}
func foobar {
delegate.doAction()
}
Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization.
The weak reference is an optional type, which means weak reference will set to nil once the instance it refers to frees from memory. On the other hand, unowned reference is a non-optional type, it never will be set to nil and always have some value.
Delegates should always generally be weak. Lets say b is the delegate of a . Now a 's delegate property is b . If c holds a strong reference to b and c deallocates, you want b to deallocate with c .
When you define a delegate object as property, it's used a weak reference in the object it is defined in(lets say A, i.e. the delegate object is a property of A). The delegate is assigned when you init A(let's say in B), then most likely you would assign A.
If your controller must be initialized with a delegate and the controller cannot work without it then unowned
is the correct solution. However, you have to make sure that the delegate is never deallocated before your controller is deallocated.
Typically, the delegate should be the owner of your controller.
However, using weak
is not complicated either:
delegate?.doAction()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With