- iOS Programming Cookbook
- Hossam Ghareeb
- 320字
- 2021-07-09 18:29:44
There's more...
The reference cycle problem can happen in situations other than relations between classes. When you use closure, there is a case where you may face a retain cycle. It happens when you assign a closure to a property in class instance and then this closure captures the instance. Let's consider the following example:
class HTMLElement { let name: String let text: String? lazy var asHTML: () -> String = { 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 } } let heading = HTMLElement(name: "h1", text: "h1 title") print(heading.asHTML()) // <h1>h1 title</h1>
We have the HTMLElement class, which has closure property asHTML. Then, we created an instance of that class which is heading, and then we called the closure to return HTML text. The code works fine, but as we said, it has a reference cycle. The instance set closure to one of its property, and the closure captures the instance (happens when we call self.name and self.text inside the closure). The closure in that case will retain self (have a strong reference to the heading instance), and at the same time, heading already has a strong reference to its property asHTML. To solve reference cycle made with closure, add the following line of code as first line in closure:
[unownedself] in
So, the class will look like this:
class HTMLElement { let name: String let text: String? lazy var asHTML: () -> String = { [unownedself] 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 } }
The unowned keyword informs the closure to use a weak reference to self instead of the strong default reference. In that case, we break the cycle and everything goes fine.
- 全屋互聯:智能家居系統開發指南
- 發布!設計與部署穩定的分布式系統(第2版)
- Mobile-first Bootstrap
- 精解Windows 8
- Implementing Azure DevOps Solutions
- 混沌工程:復雜系統韌性實現之道
- Linux就該這么學
- Windows Server 2012網絡操作系統企業應用案例詳解
- Joomla! 3 Template Essentials
- Fedora 12 Linux應用基礎
- Linux系統最佳實踐工具:命令行技術
- Windows 7使用詳解(修訂版)
- Linux 從入門到項目實踐(超值版)
- VMware vSphere 5.1 Cookbook
- Administering ArcGIS for Server