gpt4 book ai didi

swift - Swift playground 中的弱引用无法按预期工作

转载 作者:IT王子 更新时间:2023-10-29 05:43:02 25 4
gpt4 key购买 nike

我一直在关注 Playground 中 Intermediate Swift WWDC session 中的弱引用示例。我稍微修改了代码如下:

class Apartment {
let address: Int

init(address: Int) {
self.address = address
}

weak var tenant: Person?
}

class Person {
let name: String

init(name: String){
self.name = name
}

weak var home: Apartment?

func moveIn(apt: Apartment) {
self.home = apt
apt.tenant = self
}
}

var renters = ["John Appleseed": Person(name: "John Appleseed")]
var apts = [16: Apartment(address: 16)]

renters["John Appleseed"]!.moveIn(apts[16]!)
renters["John Appleseed"] = nil // memory should be released here

// then apts[16].tenant should be nil
if let tenantName = apts[16]!.tenant?.name {
// this should only execute if the Person object is still in memory
println("\(tenantName) lives at apartment number \(apts[16]!.address)")
} else {
// and this line should execute if the memory is released as we expect
println("Nobody lives at apartment number \(apts[16]!.address)")
}

// Console output in Playground: John Appleseed lives at apartment number 16
// Console output in standalone app: Nobody lives at apartment number 16

根据我对弱引用的理解,为 Person 实例分配的内存应该在从 renters 字典中删除时释放,因为对它的唯一其他引用是弱引用。但是,如果程序作为独立的命令行应用程序运行与在 Playground 中运行(请参阅评论),则程序的输出是不同的。

最佳答案

我相信顶层函数 (REPL/playground) 正在保持强大的引用以促进交互行为,并在框架返回时进行清理。此行为消除了交互式环境中的内存泄漏。

我复制了 Viktor 的简单示例并使用了 xcrun swift REPL。

在 REPL 模式下,我将逻辑包装在一个函数中,它按预期工作。如果/当您关心何时清理内存时,我建议将您的逻辑包装在一个函数中。

// declaration of the types
class Person {
let name: String
weak var home: Apartment?

init(pName: String){
name = pName
}

}

class Apartment {
let postalCode: Int

init(pPostalCode: Int) {
postalCode = pPostalCode
}
}

func testArc() {
// create Person object
var personJulius: Person = Person(pName: "Julius")

// create Apartment object
var apartmentBerlin: Apartment? = Apartment(pPostalCode: 10777)

// connect Apartment object and Person object
personJulius.home = apartmentBerlin

// Set only strong reference of Apartment object to nil
apartmentBerlin = nil

// Person object should now have nil as home
if personJulius.home != nil {
println("Julius does live in a destroyed apartment")
} else {
println("everything as it should")
}

}

//outputs "everything as it should"
testArc()

关于swift - Swift playground 中的弱引用无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24082011/

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