swift - swift 中无主的安全

标签 swift

我正在阅读 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/

相关文章:

ios - 如何将按钮添加到选项卡栏 Controller

ios - 使用未解析的标识符 'FlurryAdInterstitial'

ios - Swift 2 toInt() 不工作

ios - react swift : Observe Managed Object changes with MutableProperty

ios - 如何在文本字段中找到 UITextInput 创建的字符串(或长度)? ( swift )

swift - 为什么我要使用 CachePolicy returnCacheDataAndFetch 进行 AWS AppSync 查询?

iOS Native Camera AVFoundation亮度曝光差

ios - WKWebKit View 在 iOS 10 上重叠状态栏,但在 iOS 11 上不重叠

swift - 在 SKNode 子类中实现 anchorPoint

ios - CAGroupAnimation 不显示动画。单独添加时动画效果很好