gpt4 book ai didi

ios - Swift:在 init/deinit 中添加/删除观察者会在 Interface Builder 中引发错误

转载 作者:可可西里 更新时间:2023-11-01 01:44:22 26 4
gpt4 key购买 nike

我有一个可检查的简单 swift UI 组件 ( https://github.com/mbigatti/BMXCircularButton )。在 init/deinit 方法中,我调用了启动和停止对突出显示状态的观察。

init(frame: CGRect) {
super.init(frame: frame)
self.addObserver(self, forKeyPath: "highlighted", options: .New, context: nil)
}

init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
self.addObserver(self, forKeyPath: "highlighted", options: .New, context: nil)
}

deinit {
self.removeObserver(self, forKeyPath: "highlighted")
}

这样做会导致 Interface Builder 出现以下错误:

file:///Users/max/Progetti/StatusApp/CircularButton/CircularButton/View.xib: error: 
Live Views: Failed to update auto layout status: Interface Builder Cocoa Touch Tool raised a "NSRangeException"
exception: Cannot remove an observer <_TtC17BMXCircularButton14CircularButton 0x10ba98e00>
for the key path "highlighted" from <_TtC17BMXCircularButton14CircularButton 0x10ba98e00> because it is not registered as an observer.

file:///Users/max/Progetti/StatusApp/CircularButton/CircularButton/View.xib: error:
Live Views: Failed to render instance of _TtC17BMXCircularButton14CircularButton: Interface Builder Cocoa Touch Tool raised a "NSRangeException"
exception: Cannot remove an observer <_TtC17BMXCircularButton14CircularButton 0x10bd055d0>
for the key path "highlighted" from <_TtC17BMXCircularButton14CircularButton 0x10bd055d0> because it is not registered as an observer.

这可能是一个错误或我遗漏了什么?

最佳答案

正如 Kevin 所指出的,这里最好的答案实际上是在您的类重写中使用 didSet 和/或 willSet,因为您正在向 self 添加一个观察者。

override var highlighted:Bool {
didSet {
// Put your observerValue like code here
}
}

关于ios - Swift:在 init/deinit 中添加/删除观察者会在 Interface Builder 中引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24459587/

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