gpt4 book ai didi

Swift 不取消初始化实例

转载 作者:搜寻专家 更新时间:2023-11-01 05:32:36 24 4
gpt4 key购买 nike

我有以下代码:

class Company {
let name: String
var founder: Person?

init(name: String) {
self.name = name
print("\(self.name) was initialized")
}

deinit {
print("\(self.name) was deinitialized")
}
}

class Person {
let name: String
weak var company: Company?

init(name: String) {
self.name = name
print("\(self.name) was initialized")
}

deinit {
print("\(self.name) was deinitialized")
}
}

var mark: Person?
var facebook: Company?

mark = Person(name: "Mark Zuckerberg")
facebook = Company(name: "Facebook")
mark!.company = facebook
facebook!.founder = mark

facebook = nil
mark = nil

我对 person 的引用很弱,但它似乎仍然存在一个保留周期,因为这些实例都没有被取消初始化。它打印出初始化语句,但不打印取消初始化语句。

输出:

Mark Zuckerberg was initialized
Facebook was initialized

最佳答案

对于此示例,如果您使用可选链接分配对象变量并在代码块中实例化它们,则当没有对该对象的 strong 引用时,它们将被取消初始化。 ARC Documentation

class Company {
let name: String
var founder: Person?

init(name: String) {
self.name = name
print("\(self.name) was initialized")
}

deinit {
print("\(self.name) was deinitialized")
}
}

class Person {
let name: String
weak var company: Company?

init(name: String) {
self.name = name
print("\(self.name) was initialized")
}

deinit {
print("\(self.name) was deinitialized")
}
}

do{
var mark: Person?
var facebook: Company?

mark = Person(name: "Mark Zuckerberg")
facebook = Company(name: "Facebook")
mark?.company = facebook
facebook?.founder = mark
}

关于Swift 不取消初始化实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53185156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com