在UIAlertAction的处理程序中,自我应该被捕获为强者吗?

时间:2016-01-21 18:10:34

标签: ios swift uialertcontroller uialertaction

在撰写handler的{​​{1}}封闭时,UIAlertAction的引用是强(默认),self还是weak?< / p>

有与此主题相关的帖子(1234)但老实说,我们不知道他们是如何帮助的情况下。

让我们关注这个典型的代码:

unowned

这是func tappedQuitButton() { let alert = UIAlertController(title: "Confirm quit", message: nil, preferredStyle: .ActionSheet) let quitAction = UIAlertAction(title: "Quit", style: .Default) { (action) in self.dismissViewControllerAnimated(true, completion: nil) } alert.addAction(quitAction) let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action) in self.dismissViewControllerAnimated(true, completion: nil) } alert.addAction(cancelAction) presentViewController(alert, animated: true, completion: nil) } 子类中的一个函数,因此UIViewController是显示警报的视图控制器。

documentation说:

  

使用弱引用来避免引用循环,只要该引用可能在其生命中的某个点处具有“无值”。如果引用始终具有值,请改用无主引用。

我可能会失明,但我仍然不知道这有助于回答我关于self的问题。

在上面的代码中,UIAlertAction是否有可能在其生命中的某个时刻 ?是。所以我应该将self标记为self

但话又说回来,我无法想到一个看似合理的场景,当调用闭包时weak将为零。因此,就该关闭而言,self 将始终具有值。所以我应该将self标记为self

那么,再次,如何在UIAlertAction的处理程序中捕获unowned

1 个答案:

答案 0 :(得分:63)

要问自己的关键问题是你的警报对象是否拥有&#34;靠自己。在这种情况下,它不是(因为您在函数体中声明了let alert = ...)。因此,您不需要将其创建为弱或无主参考。

如果警报是自我的财产,那么它将被拥有&#34;通过自我,那时你想要在封闭中创建一个弱的自我引用&#34;拥有&#34;通过警报。