ios - 无主引用

标签 ios swift

使用unowned 来引用一个对象:

当对象被释放时,另一个有引用的对象被标记为unowned,那个对象也同时被释放。但是那个对象还包含对其他对象的其他引用而没有标记 unowned 呢?

class Base {
    let str: String
    init(str: String){
        self.str = str
    }
    deinit {
        print("leaving Base class with string, \(str).")
    }
}
class Country {
    let name: String
    var capitalCity: City!
    init(name: String, capitalName: String) {
        self.name = name
        self.capitalCity = City(name: capitalName, country: self)
    }
    deinit {
        print("Leaving Country class")
    }
}
class City {
    let name: String
    let baseClass: Base = Base(str: "ABC") // reference to other object.
    unowned let country: Country
    init(name: String, country: Country) {
        self.name = name
        self.country = country
    }
    deinit {
        print("Leaving City class")
    }
}
var hk: Country? = Country(name: "Hong Kong", capitalName: "Central")
let central = City(name: "Central", country: hk!)
let base = central.baseClass
print("here")
hk = nil
print("here")
print(base.str)
print("here")

//print:
//here
//Leaving Country class
//Leaving City class
//leaving Base class with string, ABC.
//here
//ABC
//here

这个对象有两个指向两个不同对象的属性。一个属性被标记为 unowned。另一个属性未标记为 unowned。因此,我认为由于其中一个属性未标记 unowned,所以它会成为一个强有力的引用。但是这个对象仍然从我的测试代码中释放。奇怪的是在解除分配后,我仍然可以访问该属性。为什么? unowned 是如何工作的?我应该如何标记它?

最佳答案

class Country {
    ...
    init(name: String, capitalName: String) {
        ...
        self.capitalCity = City(name: capitalName, country: self) // <-- o_O

你看到的“leaving Base class”central无关。

在您的Contry 的构造函数中,您已经创建了一个新的City 实例,因此也将创建一个新的Base。所以被破坏的只是hk!.capitalCity.baseClass,与central.baseClass无关。

这些与unowned无关。

关于ios - 无主引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39631117/

相关文章:

ios - Sprite Kit 逼真的骨骼动画

ios - "(NSSet *)touches"中 "event.allTouches"和 "touchesBegan:withEvent:"之间的区别

ios - 如何保存NSMutableArray来解析?

ios - 将 UIImageView 或 UITextView 添加到自定义 UIButton 类的正确方法是什么?

ios - 如何在解析网页内容时单击按钮

ios - 如果用户不存在,应该使用 UIAlert 显示错误消息

ios - NSLayoutConstraint 的幽灵困扰着我的 View 层次结构?

Swift:可选下标的可选链接

swift - BMI 计数不起作用

ios - 如何在与 OpenGL 混合的 GLKView 中绘制字符串