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

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.

主站蜘蛛池模板: 永春县| 晋江市| 安阳市| 莱阳市| 慈溪市| 大城县| 界首市| 杨浦区| 志丹县| 仁化县| 通化县| 吐鲁番市| 娄烦县| 定日县| 清远市| 阿鲁科尔沁旗| 汶上县| 民乐县| 茂名市| 浦城县| 囊谦县| 乾安县| 潮州市| 皋兰县| 青田县| 潜江市| 华宁县| 泾阳县| 二连浩特市| 孝感市| 丰镇市| 全南县| 高青县| 华容县| 康定县| 枣阳市| 南阳市| 巴中市| 柳江县| 昌乐县| 微博|