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

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
主站蜘蛛池模板: 砀山县| 大邑县| 高尔夫| 潼关县| 东明县| 理塘县| 临泉县| 砚山县| 额尔古纳市| 绿春县| 英吉沙县| 瑞昌市| 水城县| 甘孜县| 孟连| 景宁| 新民市| 高安市| 绵阳市| 曲阳县| 阳城县| 温泉县| 紫云| 牡丹江市| 东乡县| 大荔县| 宜宾县| 珲春市| 大宁县| 灵台县| 阳西县| 霸州市| 旺苍县| 凌海市| 萨嘎县| 获嘉县| 鄯善县| 博野县| 汨罗市| 西乌珠穆沁旗| 乌恰县|