我正在尝试更好地了解ARC并使用Apples Documentation
通过第一个例子,我没有得到Apple所说的预期结果; "因为弱引用并没有对它所引用的实例保持强大的保持,所以当弱引用仍然引用它时,该实例可能被释放。因此,当引用它的实例被解除分配时,ARC会自动设置对nil的弱引用。"
我在XCode 8.3.2中使用游乐场
import UIKit
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { print("\(name) is being deinitialized") }
}
class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
weak var tenant: Person?
deinit { print("Apartment \(unit) is being deinitialized") }
}
var john: Person?
var unit4A: Apartment?
john = Person(name: "John Appleseed")
unit4A = Apartment(unit: "4A")
john!.apartment = unit4A
unit4A!.tenant = john
john = nil //This prints "John Appleseed is being deinitialized" (as expected)
unit4a?.tenant?.name //This shows "John Appleseed" (expected nil)
unit4a = nil //Prints "Unit4a is being deinitialized" (as expected)
据我所知,这会阻止强大的参考周期,以便两者都可以被取消初始化,但我不明白为什么unit4a会保留对租户的引用?