在Swift中互相引用的两个弱变量? [英] Two weak variables referencing each other in Swift?

查看:71
本文介绍了在Swift中互相引用的两个弱变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天在尝试另一种尝试,以了解Swift中的保留周期和弱引用.通过阅读文档,我看到了以下代码示例,其中引用变量之一标记为weak以防止保留周期:

I'm making another attempt today to try to understand retain cycles and weak references in Swift. Reading through the documentation, I saw the following code example where one of the referencing variables is marked as weak to prevent a retain cycle:

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?             // <---- This var is marked as 'weak'
    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

john = nil // prints "John Appleseed is being deinitialized"
unit4A = nil // prints "Apartment 4A is being deinitialized"

使两个变量均变弱是否有问题?也就是说,在Person类中,我可以将apartment变量更改为弱变量以便我拥有

Is there any problem with making both variable weak? That is, in the Person class, could I change the apartment variable to be weak so that I have

class Person {
    // ...
    weak var apartment: Apartment?  // added 'weak'
    // ...
}

class Apartment {
    // ...
    weak var tenant: Person?
    // ...
}

其中有两个相互引用的弱变量.

where there are two weak variables that reference each other.

我已经在Playground中对其进行了测试,并且看起来还可以,但是是否有充分的理由不这样做呢?在这种情况下,似乎这里没有自然的亲子关系.

I tested it out in the Playground and it seems to work ok, but is there any strong reason not to do this? It seems like in this case there is no natural parent-child relationship here.

推荐答案

您可以这样做.唯一的副作用是,您需要确保其他方面能够保留住人员和公寓.在原始代码中,您只需要保留人员,公寓(与人员相关联)将为您保留.

You can do that. The only side effect is that you need to ensure that something else is retaining the people and the apartments. In the original code you just need to retain the people and the apartments (associated with people) will be retained for you.

严格来说,当公寓被拆除时,人们不会被杀死,而当人们死亡时,公寓也不会被拆除,因此这种情况下的弱引用是有道理的.通常最好考虑所需的关系和所有权模型,然后决定如何实现.

Strictly speaking the people aren't killed when the apartments are demolished and the apartments aren't demolished when the people die so weak references in this scenario make sense. It's generally better to consider the relationship and ownership model you want and then decide how to achieve that.

这篇关于在Swift中互相引用的两个弱变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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