- 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.
推薦閱讀
- SQL Server入門經(jīng)典
- 云計(jì)算環(huán)境下的信息資源集成與服務(wù)
- SQL Server 2012數(shù)據(jù)庫(kù)技術(shù)與應(yīng)用(微課版)
- 大數(shù)據(jù)可視化
- Python廣告數(shù)據(jù)挖掘與分析實(shí)戰(zhàn)
- Neural Network Programming with TensorFlow
- 大數(shù)據(jù)時(shí)代下的智能轉(zhuǎn)型進(jìn)程精選(套裝共10冊(cè))
- 3D計(jì)算機(jī)視覺(jué):原理、算法及應(yīng)用
- SAS金融數(shù)據(jù)挖掘與建模:系統(tǒng)方法與案例解析
- 數(shù)據(jù)庫(kù)技術(shù)及應(yīng)用
- 大數(shù)據(jù)數(shù)學(xué)基礎(chǔ)(R語(yǔ)言描述)
- The Natural Language Processing Workshop
- 云計(jì)算寶典:技術(shù)與實(shí)踐
- 數(shù)據(jù)指標(biāo)體系:構(gòu)建方法與應(yīng)用實(shí)踐
- 數(shù)據(jù)中臺(tái)實(shí)戰(zhàn):手把手教你搭建數(shù)據(jù)中臺(tái)