This question already has an answer here:
这个问题在这里已有答案:
- Weak references in Swift playground don't work as expected 4 answers
Swift游乐场中的弱引用无法按预期工作4个答案
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.
上面的代码片段也可以用图形表示如下。
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")
}
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.
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.
游乐场是魔鬼的工作。在真实的应用程序项目中测试,而不是游乐场,您将看到它按预期工作。