52

在编写handlera 的闭包时UIAlertAction,引用应该self是强(默认)weak、还是unowned

已经有与该主题相关的帖子(1234),但老实说,我看不出它们在这种情况下有何帮助。

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

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为零?是的。所以我应该标记为。selfweak

但是话又说回来,我想不出一个合理的场景,self当调用闭包时会为零。因此,就该闭包而言,self 将始终具有 value。所以我应该标记selfunowned

那么,再次,应该如何self在 UIAlertAction 的处理程序中捕获?

4

1 回答 1

83

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

如果 alert 是 self 的属性,那么它会被 self “拥有”,这就是当你想要在 alert “拥有”的闭包中创建对 self 的弱引用时。

于 2016-01-21T18:33:38.593 回答