Skip to content

Instantly share code, notes, and snippets.

@TerryCK
Last active July 18, 2017 03:01
Show Gist options
  • Save TerryCK/0a53de16d38db39f98baee9cd782c26d to your computer and use it in GitHub Desktop.
Save TerryCK/0a53de16d38db39f98baee9cd782c26d to your computer and use it in GitHub Desktop.
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內容
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment