使用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/