为什么要在依赖自我的地方指定[unown self]? [英] Why specify [unowned self] in blocks where you depend on self being there?

查看:157
本文介绍了为什么要在依赖自我的地方指定[unown self]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在块执行期间,我希望self不为nil,并且肯定会为nil.那么,为什么要明确指定[无主的自我]?

I want self to be non-nil and I'm sure it will be, during the blocks execution. So why explicitly specify [unowned self] ?

object.executeBlock {
    date = self.lastModified
}

vs

object.executeBlock { [unowned self] in
    date = self.lastModified
}

好吧,我的票数下降了,所以让我们再试一次.问:比方说我有问题.那个问题是我想防止参考周期.我有两个选择.我可以使用[无主的自我],也可以使用[弱的自我].因此,我的问题是:从这两个选项中,为什么我会选择[无主的自我]?为什么不每次都选择[弱自我]?

Well i'm getting down votes so let's try again. Q: Let’s say I have a problem. That problem is that I would like to prevent a reference cycle. I have two options. I could use [unowned self] or I could use [weak self]. My question therefore, is this: from these two options, why would I choose [unowned self] ? Why not choose [weak self] everytime ?

推荐答案

《语言指南》声明,如果闭包和包含对象相互引用,并且应该同时销毁,则应使用unown.安全地删除将要反分配的对象中的弱引用."

"The Language Guide claims you should use unowned if the closure and containing object reference each other and will be destroyed at the same time. Presumably that's to avoid the cost of safely nil'ing out a weak reference in an object that's about to dealloc anyway."

http://www.russbishop.net/swift-capture-lists

因此,[unown self]使self成为一个隐式解包的可选对象,以方便您自己不解包,否则可能会崩溃,如果它实际上是nil.

So [unowned self] makes self an an implicitly unwrapped optional, for the convenience of not unwrapping it yourself, at the risk of a crash if of course it is actually nil.

这篇关于为什么要在依赖自我的地方指定[unown self]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆