unowned

代码:

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

unowned 的安全处理, 在不能确定对象释放时机的情况下, 最好用 weak.

Visual Debugging with Xcode

你可能感兴趣的:(unowned)