我有这个使用弱引用的 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
代码没有执行。
最佳答案
didSet
和 willSet
不会在弱引用因 ARC 自动归零时被调用。
如果您手动将属性设置为 nil
,您会看到调用了 didSet
代码。
关于swift - didSet for weak reference 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33270630/