- 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.
推薦閱讀
- Unity 5.x Game AI Programming Cookbook
- PySpark大數據分析與應用
- Mastering Machine Learning with R(Second Edition)
- 智能數據分析:入門、實戰與平臺構建
- 金融商業算法建模:基于Python和SAS
- 數據科學工程實踐:用戶行為分析與建模、A/B實驗、SQLFlow
- 云數據中心網絡與SDN:技術架構與實現
- SQL Server 2012數據庫管理教程
- 數據科學實戰指南
- HikariCP連接池實戰
- Power BI智能數據分析與可視化從入門到精通
- Hands-On System Programming with C++
- Internet of Things with Python
- 信息融合中估計算法的性能評估
- 數據挖掘算法實踐與案例詳解