- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 132字
- 2021-07-02 14:44:59
Using closures as callbacks
Functions and closures can capture the current scope, which means all of the declared variables outside of the function or closure definition, such as local variables or self. In the case of self, you can inadvertently extended the lifetime of your objects and leak memory:
class MyClass {
var running = false
func run() {
running = true
DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
self.running = false
}
}
}
var instance: MyClass? = MyClass()
instance?.run()
instance = nil
Can you spot the potential issue in this code?
Depending on the use case, you may want instance to be destroyed when it is not referenced by any owner. In our case, we'll probably cause a memory leak, as the dispatch block is referencing self without any memory management qualifier.
推薦閱讀
- Python絕技:運用Python成為頂級數據工程師
- 從零開始學Hadoop大數據分析(視頻教學版)
- Architects of Intelligence
- 算法與數據中臺:基于Google、Facebook與微博實踐
- Hadoop大數據實戰權威指南(第2版)
- 數亦有道:Python數據科學指南
- 金融商業算法建模:基于Python和SAS
- Construct 2 Game Development by Example
- IPython Interactive Computing and Visualization Cookbook(Second Edition)
- 編寫有效用例
- SQL Server深入詳解
- 爬蟲實戰:從數據到產品
- R Object-oriented Programming
- 計算機視覺
- Mastering ROS for Robotics Programming(Second Edition)