代码1:
class A {
func run(block: (() -> ())) {
block()
}
}
autoreleasepool {
let a = A()
a.run {
[unowned a] in
DispatchQueue.global().async {
sleep(1)
print(a)
}
}
}
sleep(2)
// print
Fatal error: Attempted to read an unowned reference but object 0x6020000009d0 was already deallocated2020-10-15 15:32:42.407153+0800 SwiftCmdTest[34061:2963287] Fatal error: Attempted to read an unowned reference but object 0x6020000009d0 was already deallocated
Fatal error: Attempted to read an unowned reference but object 0x6020000009d0 was already deallocated
代码2:
class A {
func run(block: (() -> ())) {
block()
}
}
autoreleasepool {
let a = A()
a.run {
[unowned a] in
let aa = a
DispatchQueue.global().async {
sleep(1)
print(aa)
}
}
}
sleep(2)
// print
SwiftCmdTest.A
对比代码1, 代码2, unowned 的安全处理, 在不能确定对象释放时机的情况下, 最好用 weak, unowned 对 a.block = { [unowned a] in }
这种情况可以采用上面代码2处理方式, 延迟释放.
网友评论