Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weak vs Unowned for non-optional delegates

Tags:

ios

swift

swift2

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()
  }
like image 903
meow Avatar asked Aug 23 '16 08:08

meow


People also ask

When to use weak and unowned in Swift?

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.

What is the difference between weak and unowned?

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.

Should delegates always be weak?

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 .

Why is delegate weak in iOS?

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.


1 Answers

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()
like image 134
Sulthan Avatar answered Oct 05 '22 13:10

Sulthan