在Swift中通过闭包捕获时,不会释放对象

时间:2014-06-10 08:10:22

标签: ios closures swift dealloc

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()方法中打印出字符串,但它没有打印任何内容。对我来说,对象仍然存在,并且与闭包有很强的参考周期。有没有人得到同样的问题?

1 个答案:

答案 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