swift - 为什么调用 deinit 方法后可以访问对象?

标签 swift swift3 automatic-ref-counting

我从 Swift 指南中的无主引用部分复制了大部分代码,并在 Playground 中运行它......

class Customer {
    let name: String
    var card: CreditCard?

    init(name: String) {
        self.name = name
    }
    deinit { print("\(name) is being “deinitialized") }
}

class CreditCard {
    let number: UInt64
    unowned let customer: Customer
    init(number: UInt64, customer: Customer) {
        self.number = number
        self.customer = customer
    }
    deinit { print("Card #\(number) is being deinitialized") }
}

var john: Customer?

john = Customer(name: "John Appleseed")
john!.card = CreditCard(number: 1234_5678_9012_3456, customer: john!)

var card = john!.card!

john = nil

card.customer.name

john 设置为 nil 结果...

"John Appleseed is being “deinitialized\n"

但是获取 name 属性会给出...

"John Appleseed"

因此,尽管已取消初始化,客户实例仍然可以访问!

这不应该导致零引用异常吗?指南中说...

Note also that Swift guarantees your app will crash if you try to access an unowned reference after the instance it references is deallocated. You will never encounter unexpected behavior in this situation. Your app will always crash reliably, although you should, of course, prevent it from doing so.

所以,我认为它一定没有被释放。然而,指南还说,

A deinitializer is called immediately before a class instance is deallocated.

最佳答案

代码在常规项目中按预期工作,而不是在 Playground 中。

关于swift - 为什么调用 deinit 方法后可以访问对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40403074/

相关文章:

swift - 如何在不使用内置撤消管理器的情况下撤消 NSManagedObject 删除?

swift - Struct 不符合 RawRepresentable 协议(protocol)?

ios - 功能执行延迟(请求访问权限后)IOS

iOS - 引用 UIViewController 对象的自定义类

ios - CGImageRef 未在 ARC 下发布

swift - 如何在 Swift 中获取 "Any?"变量的真实类型

swift - 从 Swift 通用函数返回文字值?

arrays - Swift3:泛型扩展中的类型推断

IOS swift 如何使用 UIActivityViewController 共享图像和文本

ios - 带有 ARC 的 Objective C 中的对象数组