延迟初始化并保留周期

编程入门 行业动态 更新时间:2024-10-09 16:27:39
本文介绍了延迟初始化并保留周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

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

更多推荐

延迟初始化并保留周期

本文发布于:2023-11-12 01:55:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580181.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   周期

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!