Last active
July 18, 2017 02:57
-
-
Save TerryCK/4b2db60d77bb9d41a072db410751f5ac to your computer and use it in GitHub Desktop.
Closure retain cycle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HTMLElement { | |
let name: String | |
let text: String | |
// 參考self的closure造成 記憶體無法釋放的retain cycle | |
lazy var asHTML: () -> String = { | |
return "<\(self.name)>\(self.text)</\(self.name)>" | |
} | |
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