Eri*_*ric 43 ios swift uialertcontroller uialertaction
当写一个handler关闭的时候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)
}
Run Code Online (Sandbox Code Playgroud)
这是UIViewController子类内部的一个函数,self视图控制器也会显示警报.
该文件说:
只要该引用可能在其生命中的某个点上具有"无值",就使用弱引用来避免引用循环.如果引用始终具有值,请改用无主引用.
我可能会失明,但我仍然没有看到这有助于回答我的问题UIAlertAction.
在上面的代码中,是否有可能在其生命中的某个时刻self为零?是.所以我应该标记为.selfweak
但话又说回来,我想不出一个看似合理的场景,self当闭合被召唤时,它将是零.因此,就该关闭而言,self 将始终具有价值.所以我应该标记self为unowned.
那么,再次,如何self在UIAlertAction的处理程序中捕获它?
Goo*_*oug 67
问自己的关键问题是你的警报对象是否由自己"拥有".在这种情况下,它不是(因为你let alert = ...在函数体中声明).因此,您不需要将其创建为弱或无主参考.
如果alert是self的一个属性,那么它将由self"拥有",那时你想要在alert"拥有"的闭包中创建一个弱的self引用.
| 归档时间: |
|
| 查看次数: |
6070 次 |
| 最近记录: |