Property is unable to set to nil via weak reference [duplicate]

安稳与你 提交于 2021-01-29 03:56:58

问题


The following code defines Person and Apartment. Person instance may own an Apartment, Apartment may have a tenant(Person instance)

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

The code snippet above can also be represented graphically as follows.

Now the following code is executed to deallocated instance 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")
}

Problem: Xcode doesn't set tenant property to nil (please see the last figure)

Question: How can I fix it? I've tried the code on IBM Swift SandBox and it works well, Xcode has a bug?

Many thanks.


回答1:


Playgrounds are the work of the devil. Test in a real app project, not a playground, and you will see that this works as you expect.



来源:https://stackoverflow.com/questions/38397502/property-is-unable-to-set-to-nil-via-weak-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!