属性无法通过弱引用设置为nil

时间:2016-07-15 13:35:49

标签: swift memory-management xcode7 weak-references

以下代码定义PersonApartmentPerson个实例可能拥有ApartmentApartment可能拥有租户(Person个实例)

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

上面的代码片段也可以用图形表示如下。 enter image description here

现在执行以下代码以解除分配实例john

john = nil

if let per = unit4A!.tenant {
    print("\(per.name) is a ghost person") \\This line is prented out, isn't it already a set with `nil`?
} else {
    print("all nil dude")
}

enter image description here

问题: Xcode没有将tenant属性设置为nil(请参阅上图)

问题:我该如何解决?我已经尝试了IBM Swift SandBox上的代码并且效果很好,Xcode有错误吗?

非常感谢。

enter image description here

1 个答案:

答案 0 :(得分:1)

游乐场是魔鬼的作品。在真实的应用程序项目中测试,而不是在游乐场中进行测试,您将看到它按预期工作。