官术网_书友最值得收藏!

  • 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.

主站蜘蛛池模板: 黄梅县| 大化| 安图县| 随州市| 新田县| 永平县| 长寿区| 台南县| 盐津县| 新密市| 滁州市| 搜索| 志丹县| 安龙县| 冕宁县| 永新县| 荃湾区| 华容县| 肥西县| 略阳县| 新晃| 晋城| 临高县| 万全县| 二手房| 白玉县| 屏边| 溆浦县| 蓬溪县| 孟村| 桦甸市| 黄石市| 安龙县| 正安县| 遵义县| 思南县| 栖霞市| 监利县| 景德镇市| 化隆| 房产|