gpt4 book ai didi

swift - didSet for weak reference 没有按预期工作

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:42 26 4
gpt4 key购买 nike

我有这个使用弱引用的 Swift 小脚本:

#!/usr/bin/env swift

class Thing
{
deinit
{
print("Thing object deallocated")
}
}

class WeakThing
{
weak var thing: Thing?
{
didSet
{
print("Set thing to \(thing)")
}
}
}

var thing = Thing()

let weakThing = WeakThing()
weakThing.thing = thing

thing = Thing()
print("weakThing's thing is \(weakThing.thing)")

这打印:

Set thing to Optional(Test.Thing)
Thing object deallocated
weakThing's thing is nil

但是,我希望它打印:

Set thing to Optional(Test.Thing)
Set thing to nil
Thing object deallocated
weakThing's thing is nil

我做错了什么?我看到对象正在被释放,并且 thing 变量的值正在改变,但我的 didSet 代码没有执行。

最佳答案

didSetwillSet 不会在弱引用因 ARC 自动归零时被调用。

如果您手动将属性设置为 nil,您会看到调用了 didSet 代码。

关于swift - didSet for weak reference 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33270630/

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