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

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.

主站蜘蛛池模板: 沙湾县| 鄄城县| 调兵山市| 安图县| 惠东县| 盐边县| 买车| 洪泽县| 洞口县| 黄平县| 加查县| 扎兰屯市| 连云港市| 连云港市| 天峻县| 延边| 共和县| 昭觉县| 文昌市| 团风县| 于都县| 嘉兴市| 华阴市| 改则县| 仙桃市| 磴口县| 赞皇县| 巴中市| 宜丰县| 宣威市| 内丘县| 四平市| 佛冈县| 红桥区| 开远市| 朔州市| 醴陵市| 威信县| 漠河县| 恩施市| 会理县|