在编写handler
a 的闭包时UIAlertAction
,引用应该self
是强(默认)weak
、还是unowned
?
已经有与该主题相关的帖子(1、2、3、4),但老实说,我看不出它们在这种情况下有何帮助。
让我们关注这个典型的代码:
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
这是子类中的一个函数,self
呈现警报的视图控制器也是如此。
文档说:
使用弱引用来避免引用循环,只要该引用在其生命周期的某个时间点可能“没有价值”。如果引用总是有值,请改用无主引用。
我可能是盲人,但我仍然不明白这对回答我的问题有何帮助UIAlertAction
。
在上面的代码中,是否有可能在其生命中的某个时刻self
为零?是的。所以我应该标记为。self
weak
但是话又说回来,我想不出一个合理的场景,self
当调用闭包时会为零。因此,就该闭包而言,self
将始终具有 value。所以我应该标记self
为unowned
。
那么,再次,应该如何self
在 UIAlertAction 的处理程序中捕获?