问题描述
使用惰性初始化程序时,是否有保留周期的机会?
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.
推荐答案
lazy var personalizedGreeting: String = { return self.name }()
正确.
原因是,立即应用的闭包{}()
被视为@noescape
.它不会保留捕获的self
.
The reason is that the immediately applied closure {}()
is considered @noescape
. It does not retain the captured self
.
供参考:乔·格罗夫的推文.
这篇关于延迟初始化并保留周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!