- 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.
推薦閱讀
- 數據產品經理高效學習手冊:產品設計、技術常識與機器學習
- 信息系統與數據科學
- 大數據可視化
- 新型數據庫系統:原理、架構與實踐
- OracleDBA實戰攻略:運維管理、診斷優化、高可用與最佳實踐
- 企業級數據與AI項目成功之道
- 數據挖掘原理與SPSS Clementine應用寶典
- 數字媒體交互設計(初級):Web產品交互設計方法與案例
- 高維數據分析預處理技術
- Web Services Testing with soapUI
- Unity 2018 By Example(Second Edition)
- Python數據分析從小白到專家
- 菜鳥學SPSS數據分析
- Mastering ROS for Robotics Programming(Second Edition)
- 智能與數據重構世界