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

标签 swift weak-references

我有这个使用弱引用的 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/

相关文章:

string - 什么是 Swift String 到 NSString 的桥接开销?

c# - WeakReference 在 Debug 和 Release 中表现不同(没有附加调试器)。即使使用工厂方法

ios - 如何混淆 cocoa touch 框架代码? ( swift 4)

ios - 复合过滤器数组的 Realm 查询

ios - IBoutlet 如何保持初始值变弱?意味着其他一些强大的物体指向?

swift - swift 闭包中的 self 引用在一段时间内返回 nil

java - 迭代 WeakHashMap

ios - 当弱引用对象(任意类型)被释放时,我可以 Hook 吗?

swift - 我正在尝试在用户输入时查询 firebase 数据库,但我不断收到此错误

ios - 以编程方式使用 ScrollView