- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 186字
- 2021-07-02 14:45:07
Using weak
Using weak will ensure that we never create a strong reference in ref, but will not retain the objects, either. If the object passed in ref is never retained by any other object, it will automatically be deallocated. This will lead to unexpected behavior, as the chain will be deallocated, and only a returned object will be kept in the memory:
class MemoryLeak {
weak var ref: MemoryLeak?
init(ref: MemoryLeak) {
self.ref = ref
}
init() {
ref = self
}
}
func test() -> MemoryLeak {
let a = MemoryLeak()
let b = MemoryLeak(ref: a)
let c = MemoryLeak(ref: b)
a.ref = c
return a
}
let result = test()
assert(result.ref != nil)
In the preceding code, we changed the MemoryLeak class, in order to keep a weak reference in ref. Unfortunately, the program will crash at the assertion line, as the ref property will be deallocated.
This is often the behavior that you are looking for with delegation. Using weak for the delegate lets you safely avoid thinking about the potential reference cycle; however, the delegates should be retained on their own.
推薦閱讀
- 數據庫應用實戰
- 云數據中心基礎
- Spark大數據分析實戰
- Learning JavaScriptMVC
- PySpark大數據分析與應用
- 數據庫系統原理及應用教程(第4版)
- 數據庫應用基礎教程(Visual FoxPro 9.0)
- INSTANT Cytoscape Complex Network Analysis How-to
- 基于Apache CXF構建SOA應用
- 數字媒體交互設計(初級):Web產品交互設計方法與案例
- Proxmox VE超融合集群實踐真傳
- 數據中心數字孿生應用實踐
- 淘寶、天貓電商數據分析與挖掘實戰(第2版)
- Google Cloud Platform for Developers
- 一本書講透Elasticsearch:原理、進階與工程實踐