- 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.
推薦閱讀
- 有趣的二進(jìn)制:軟件安全與逆向分析
- DB29forLinux,UNIX,Windows數(shù)據(jù)庫管理認(rèn)證指南
- 輕松學(xué)大數(shù)據(jù)挖掘:算法、場(chǎng)景與數(shù)據(jù)產(chǎn)品
- Access 2007數(shù)據(jù)庫應(yīng)用上機(jī)指導(dǎo)與練習(xí)
- Enterprise Integration with WSO2 ESB
- 大數(shù)據(jù)營(yíng)銷:如何讓營(yíng)銷更具吸引力
- 數(shù)字媒體交互設(shè)計(jì)(初級(jí)):Web產(chǎn)品交互設(shè)計(jì)方法與案例
- Starling Game Development Essentials
- 數(shù)據(jù)庫原理與設(shè)計(jì)(第2版)
- Proxmox VE超融合集群實(shí)踐真?zhèn)?/a>
- 大數(shù)據(jù)精準(zhǔn)挖掘
- Instant Autodesk AutoCAD 2014 Customization with .NET
- 改變未來的九大算法
- Microsoft Dynamics NAV 2015 Professional Reporting
- 一本書讀懂大數(shù)據(jù)