简体   繁体   English

非可选代表的弱者与无者

[英]Weak vs Unowned for non-optional delegates

If my viewcontroller must be initialized with a delegate, is there any danger at all to doing using an unowned instead? 如果必须使用委托初始化我的viewcontroller,那么使用unown代替存在所有危险吗?

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? 无论如何,在这种情况下使用unown是不安全的吗?

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()
  }

The Apple Documentation says 苹果文档

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. 相反,当您知道在初始化期间将其设置为零时,请使用无主引用。

So in your case, if you know that the delegate will be there for the whole lifetime then use unowned . 因此,在您的情况下,如果您知道委托将在整个生命周期中都存在,则请使用unowned

The difference between weak and unowned is that weak can be nil and unowned cannot be nil. weakunowned之间的区别在于,弱者可以为零,而无人不能为零。 Both do not add to the retain cycle and there is no danger with unowned as long as you do not deallocate the delegate. 两者都不会增加保留周期,并且只要您不取消分配委托,就不会有未unowned危险。

If your controller must be initialized with a delegate and the controller cannot work without it then unowned is the correct solution. 如果您的控制器必须使用委托进行初始化,并且如果没有委托则控制器无法工作,那么unowned是正确的解决方案。 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: 但是,使用weak并不复杂:

delegate?.doAction()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM