Weak vs. Unowned for Optional Delegates

If my view manager needs to be initialized by a delegate, is there any danger to using it instead without the right to use it?

The use of weak ones, apparently, leads to the probability of failure of functions (see below), although this will not lead to failure.

In any case, the use of invalid in this case is unsafe?

class MyViewController: UIViewController private weak var delegate: MyViewControllerDelegate? init(delegate: MyViewControllerDelegat) { self.delegate = delegate } func foobar { delegate?? } 

compared with

 class MyViewController: UIViewController private unowned var delegate: MyViewControllerDelegate init(delegate: MyViewControllerDelegate) { self.delegate = delegate } func foobar { delegate.doAction() } 
+5
source share
2 answers

If your controller needs to be initialized by a delegate, and the controller cannot work without it, then unowned is the right solution. However, you must make sure that the delegate is never released before your controller is released. Typically, a delegate should be the owner of your controller.

However, using weak also not complicated:

 delegate?.doAction() 
+2
source

Apple Documentation says

Use a weak link when it’s valid for that link to become nil at some point in your life. Conversely, use unowned if you know that the link will never be zero was set during initialization.

So, in your case, if you know that a delegate will be present throughout the entire service life, use unowned .

The difference between weak and unowned is that the weak can be nil and unowned cannot be nil. Both of them do not add to the save loop, and there is no danger with unowned until you free the delegate.

+2
source

All Articles