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

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.

主站蜘蛛池模板: 信阳市| 武山县| 海林市| 保靖县| 上栗县| 晋中市| 天柱县| 建德市| 盘锦市| 南江县| 鄂伦春自治旗| 历史| 涟源市| 饶河县| 洛隆县| 太仆寺旗| 咸宁市| 西青区| 安义县| 沅江市| 凤山市| 安庆市| 龙川县| 贵南县| 延庆县| 文化| 孟州市| 长沙县| 灵川县| 綦江县| 巴彦淖尔市| 茶陵县| 海阳市| 寿宁县| 绥芬河市| 黑河市| 扶风县| 昭觉县| 遂平县| 平潭县| 奇台县|