在UIAlertAction的处理程序中,自我应该被捕获为强者吗? [英] Should self be captured as strong in a UIAlertAction's handler?
问题描述
当写处理程序
关闭 UIAlertAction
时,应该引用 self
强(默认),弱
,或无主
?
When writing the handler
closure of a UIAlertAction
, should the reference to self
be strong (the default), weak
, or unowned
?
有与此主题相关的帖子( 1 , 2 , 3 , 4 )但老实说,在这种情况下我不明白他们是如何帮助的。
There have been posts relevant to this topic (1, 2, 3, 4) but I honestly don't see how they help in this case.
让我们关注这个典型的代码:
Let's focus on this typical code:
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
是视图控制器提示警报。
This is a function inside a UIViewController
subclass, so self
is the view controller presenting the alert.
文档说:
使用弱引用来避免引用周期参考没有价值在其生命的某个方面。如果引用始终具有值,请改用无主引用。
Use a weak reference to avoid reference cycles whenever it is possible for that reference to have "no value" at some point in its life. If the reference will always have a value, use an unowned reference instead.
我可能会失明,但我仍然看不出这有助于回答我关于 UIAlertAction <的问题/ code>。
I may be blind, but I still don't see how this helps answering my question about UIAlertAction
.
在上面的代码中, self
是否有可能在其生命的某个时刻为 ?是。所以我应该将 self
标记为 weak
。
In the above code, is it possible for self
to be nil at some point in its life? Yes. So I should mark self
as weak
.
但是然后再次,我想不出一个看似合理的情况,当调用闭包时, self
将为nil。因此,就该关闭而言, self
将始终具有值。所以我应该将 self
标记为无主
。
But then again, I can't think of a plausible scenario where self
will be nil when the closure is called. So as far as that closure is concerned, self
will always have a value. So I should mark self
as unowned
.
那么,再次,如何在UIAlertAction的处理程序中捕获 self
?
So, again, how should self
be captured in a UIAlertAction's handler?
推荐答案
要问自己的关键问题是你的警报对象是否由自己拥有。在这种情况下,它不是(因为你在函数体中声明了 let alert = ...
)。因此,您不需要将其创建为弱或无主参考。
The key question to ask yourself is if your alert object is "owned" by self. In this case, it is not (because you declared let alert = ...
in the function body). So you do not need to create this as a weak or unowned reference.
如果alert是self的属性,那么它将由self拥有,即当你想要在警报的拥有的闭包中创建一个弱的自我引用时。
If alert was a property of self, then it would be "owned" by self and that is when you would want to create a weak reference to self in the closure "owned" by the alert.
这篇关于在UIAlertAction的处理程序中,自我应该被捕获为强者吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!