Swift编程语言指南有以下示例:
class HTMLElement {
let name: String
let text: String?
@lazy var asHTML: () -> String = {
[unowned self] in
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit {
println("\(name) is being deinitialized")
}
}
var paragraph:HTMLElement? = HTMLElement(name: "p", text: "hello, world")
println("\(paragraph!.asHTML())")
paragraph = nil
预计会在deinit()方法中打印出字符串,但它没有打印任何内容。对我来说,对象仍然存在,并且与闭包有很强的参考周期。有没有人得到同样的问题?
答案 0 :(得分:2)
使用弱捕获而非无主
执行此操作class HTMLElement {
let name: String
let text: String?
@lazy var asHTML: () -> String = {
[weak self] in
if let text = self?.text {
return "<\(self?.name)>\(text)</\(self?.name)>"
} else {
return "<\(self?.name) />"
}
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit {
println("\(name) is being deinitialized")
}
}
var paragraph:HTMLElement? = HTMLElement(name: "p", text: "hello, world")
println("\(paragraph!.asHTML())")
paragraph = nil