我从 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/