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

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
主站蜘蛛池模板: 天津市| 贵南县| 古交市| 浏阳市| 休宁县| 嘉义县| 孝昌县| 武强县| 宜川县| 江山市| 卢龙县| 泌阳县| 出国| 获嘉县| 白城市| 衡山县| 富阳市| 仁寿县| 台南县| 岢岚县| 武冈市| 西林县| 出国| 鹿泉市| 营山县| 垫江县| 宜良县| 千阳县| 碌曲县| 台东市| 娄底市| 安吉县| 积石山| 灵台县| 平武县| 龙门县| 上饶县| 光泽县| 榆社县| 宣城市| 堆龙德庆县|