- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 223字
- 2021-07-02 14:44:59
Using weak and unowned
Swift provides us with two keywords that indicate how we want to extend the lifetime of an object in a closure. While both prevent creating retain cycles, they are fundamentally different.
Using weak will wrap the captured value inside of an optional, indicating that the instance may have been deallocated before the closure was executed:
class MyClass {
var running = false
func run() {
running = true
DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [weak self] in
self?.running = false
}
}
}
var instance: MyClass? = MyClass()
instance?.run()
instance = nil
In this execution, instance will immediately be deallocated when set to nil.
Using unowned indicates that the variable won't be owned by the block. Another mechanism should be responsible for ensuring that the lifetime of the captured object is properly extended until the block is executed:
class MyClass {
var running = false
func run() {
running = true
DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [unowned self] in
self.running = false
}
}
}
var instance: MyClass? = MyClass()
instance?.run()
instance = nil
In this case, your program will crash when the block is executing, because the self variable will be deallocated upon the execution of the block:
Fatal error: Attempted to read an unowned reference but object 0x7f80bc75a4e0 was already deallocated
- 漫話大數據
- 有趣的二進制:軟件安全與逆向分析
- Starling Game Development Essentials
- SQL優化最佳實踐:構建高效率Oracle數據庫的方法與技巧
- Chef Essentials
- 計算機組裝與維護(微課版)
- Mastering LOB Development for Silverlight 5:A Case Study in Action
- 貫通SQL Server 2008數據庫系統開發
- 大數據數學基礎(Python語言描述)
- Filecoin原理與實現
- 數據應用工程:方法論與實踐
- 一本書讀懂大數據
- 大數據用戶行為畫像分析實操指南
- Oracle數據庫性能優化的藝術
- 用戶畫像:平臺構建與業務實踐