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

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
主站蜘蛛池模板: 德庆县| 长子县| 蓝山县| 林甸县| 珠海市| 鹤山市| 苍南县| 蚌埠市| 绥中县| 彝良县| 湘潭市| 正镶白旗| 兴仁县| 云安县| 南城县| 焉耆| 绩溪县| 桐庐县| 藁城市| 竹溪县| 民丰县| 庄浪县| 巢湖市| 德保县| 古蔺县| 顺义区| 徐州市| 浏阳市| 盐池县| 鞍山市| 德惠市| 南和县| 三门县| 嵊泗县| 新巴尔虎左旗| 芒康县| 乌拉特后旗| 柘城县| 化州市| 太原市| 谢通门县|