我正在阅读 apple docs 中关于 unowned
的内容。
Like weak references, an unowned reference does not keep a strong hold on the instance it refers to. Unlike a weak reference, however, an unowned reference is assumed to always have a value. Because of this, an unowned reference is always defined as a nonoptional type.
所以看起来 unowned 类似于 weak 但它们是非可选的。
我想知道当引用的 unowned 被释放时会发生什么。为什么没有像 optionals 这样的支票。
我的意思是我可以做这样的事情,
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 card: CreditCard? = nil
do {
var john: Customer
john = Customer(name: "John Appleseed")
john.card = CreditCard(number: 1234_5678_9012_3456, customer: john)
card = john.card
}
print("Card belongs to \(card?.customer.name)")
在最后一行假设 unowned
总是有一个值尝试打印持卡人的名字,我得到一个“执行被中断,原因:EXE_BREAKPOINT ...”
我想应该不会有这样的问题,或者应该在 card = john.card
行进行某种安全检查
最佳答案
unowned
的检查版本已经存在 - 它被称为 weak
。这是主要区别。 unowned
是不安全的,但在某些情况下它可以使您的代码更清晰。
关于swift - swift 中无主的安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36915524/