属性无法通过弱引用设置为nil [重复]

时间:2022-09-06 20:21:57

This question already has an answer here:

这个问题在这里已有答案:

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

以下代码定义了Person和Apartment。人员实例可能拥有公寓,公寓可能拥有租户(人员实例)

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. 属性无法通过弱引用设置为nil [重复]

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

Now the following code is executed to deallocated instance john

现在,执行以下代码以释放实例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")
}

属性无法通过弱引用设置为nil [重复]

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

问题:Xcode没有将租户属性设置为nil(请参见上图)

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

问题:我该如何解决?我已经尝试过IBM Swift SandBox上的代码并且运行良好,Xcode有错误吗?

Many thanks.

属性无法通过弱引用设置为nil [重复]

1 个解决方案

#1


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.

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

#1


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.

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