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

Using weak and unowned

Swift provides us with two keywords that indicate how we want to extend the lifetime of an object in a closure. While both prevent creating retain cycles, they are fundamentally different.

Using weak will wrap the captured value inside of an optional, indicating that the instance may have been deallocated before the closure was executed:

class MyClass {
var running = false
func run() {
running = true
DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [weak self] in
self?.running = false
}
}
}

var instance: MyClass? = MyClass()
instance?.run()
instance = nil

In this execution, instance will immediately be deallocated when set to nil.

Using unowned indicates that the variable won't be owned by the block. Another mechanism should be responsible for ensuring that the lifetime of the captured object is properly extended until the block is executed:

class MyClass {
var running = false
func run() {
running = true
DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [unowned self] in
self.running = false
}
}
}

var instance: MyClass? = MyClass()
instance?.run()
instance = nil

In this case, your program will crash when the block is executing, because the self variable will be deallocated upon the execution of the block:

Fatal error: Attempted to read an unowned reference but object 0x7f80bc75a4e0 was already deallocated
主站蜘蛛池模板: 金乡县| 德兴市| 大荔县| 桂平市| 克拉玛依市| 永靖县| 团风县| 南和县| 资讯 | 阜南县| 依兰县| 宜阳县| 寿宁县| 江都市| 镶黄旗| 西畴县| 祁阳县| 金华市| 杭州市| 鲜城| 元阳县| 安徽省| 德格县| 乌审旗| 炉霍县| 察隅县| 通化市| 灵川县| 康保县| 靖西县| 新竹市| 福建省| 五华县| 榆林市| 肃宁县| 五峰| 河曲县| 濮阳市| 临湘市| 紫金县| 阿荣旗|