延迟初始化并保留周期 [英] Lazy initialisation and retain cycle

查看:78
本文介绍了延迟初始化并保留周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用惰性初始化程序时,是否有保留周期的机会?

While using lazy initialisers, is there a chance of having retain cycles?

博客文章和许多其他地方[unowned self]被看到

In a blog post and many other places [unowned self] is seen

class Person {

    var name: String

    lazy var personalizedGreeting: String = {
        [unowned self] in
        return "Hello, \(self.name)!"
        }()

    init(name: String) {
        self.name = name
    }
}

我尝试过

class Person {

    var name: String

    lazy var personalizedGreeting: String = {
        //[unowned self] in
        return "Hello, \(self.name)!"
        }()

    init(name: String) {
        print("person init")
        self.name = name
    }

    deinit {
        print("person deinit")
    }
}

像这样使用它

//...
let person = Person(name: "name")
print(person.personalizedGreeting)
//..

并发现已记录人员deinit".

And found that "person deinit" was logged.

因此,似乎没有保留周期. 据我所知,当一个块捕获自身时,以及当该块被自身强烈保留时,会有一个保留周期.这种情况似乎类似于保留周期,但实际上并非如此.

So it seems there are no retain cycles. As per my knowledge when a block captures self and when this block is strongly retained by self, there is a retain cycle. This case seems similar to a retain cycle but actually it is not.

推荐答案

我尝试过此[...]

I tried this [...]

lazy var personalizedGreeting: String = { return self.name }()

似乎没有保留周期

it seems there are no retain cycles

正确.

原因是,立即应用的闭包{}()被视为@noescape.它不会保留捕获的self.

The reason is that the immediately applied closure {}() is considered @noescape. It does not retain the captured self.

供参考:乔·格罗夫的推文.

这篇关于延迟初始化并保留周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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