TerryCK
7/18/2017 - 2:59 AM

ClosureRetainCycle Resolve

ClosureRetainCycle Resolve


class HTMLElement {
    let name: String
    let text: String
    
    
    lazy var asHTML: () -> String = {
        [weak self] in  //以弱參考修飾捕獲的self使參考計數不計
        return "<\(self?.name)>\(self?.text)</\(self?.name)>",// 因為weak是弱參考屬optional所以在鏈上需要加入?使用
    }
    
    init(name: String, text: String) {
        self.name = name
        self.text = text
    }
    
    deinit {
         print("HTMLElement \(name) is bring deallocated")
    }
}


var paragraph: HTMLElement? = HTMLElement(name: "p", text: "some smaple paragraph body text")



paragraph?.asHTML()
paragraph = nil // 解決 retain cycle 執行 解構deinit內容