属性无法通过弱引用设置为零 [英] Property is unable to set to nil via weak reference

查看:53
本文介绍了属性无法通过弱引用设置为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码定义了PersonApartment.Person 实例可能拥有一个 ApartmentApartment 可能有一个租户(Person 实例)

class Person {让名称:字符串init(name: String) { self.name = name }var 公寓:公寓?deinit { print("\(name) 正在被取消初始化") }}类公寓{让单位:字符串init(unit: String) { self.unit = unit }弱变种租户:人?deinit { print("Apartment \(unit) is being deinitialized") }}var john:人?var unit4A:公寓?约翰 = 人(姓名:约翰·苹果籽")unit4A = 公寓(单位:4A")约翰!.公寓 = unit4Aunit4A!.tenant = 约翰

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

现在执行以下代码来释放实例john

john = nil如果让 per = unit4A!.tenant {print("\(per.name) is a ghost person") \\这行打印出来了,不是已经有`nil`的集合了吗?} 别的 {打印(全是零伙计")}

问题: Xcode 没有将 tenant 属性设置为 nil(请看最后一张图)

问题:我该如何解决?我已经在

解决方案

游乐场是魔鬼的杰作.在真正的应用项目中进行测试,而不是在操场上进行测试,您会发现它按预期工作.

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.

解决方案

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.

这篇关于属性无法通过弱引用设置为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆