gpt4 book ai didi

Swift KVO 在符合协议(protocol)的对象上

转载 作者:搜寻专家 更新时间:2023-11-01 06:25:22 32 4
gpt4 key购买 nike

我有一个协议(protocol) (X) 和一个实现协议(protocol) X 的类 (A):

protocol X, NSObjectProtocol {
var toBeObserved: MyCustomClass? { get}
}

class A: NSObject, X {
var toBeObserved: MyCustomClass?
...
}

在另一个类中我想观察变量toBeObserved:

class B {
...
var instanceConformingToX: X <-note: not A but simply the protocol X
...
func someFunc() {
self.observation = self.observe(\.instanceConformingToX.toBeObserved) { (observed, change) in
...
}
}
}

这里等式的每一部分都是或符合 NSObject,所以我希望能够 KVO toBeObserved 但我却遇到了运行时崩溃:

Fatal error: Could not extract a String from KeyPath Swift.KeyPath<MyAppName.B, MyFramework.A>

谢谢。

最佳答案

确保将观察到的属性标记为@objcdynamic。作为Using Key-Value Observing in Swift说:

Mark properties that you want to observe through key-value observing with both the @objc attribute and the dynamic modifier.

协议(protocol)和参与类也需要标记为@objc。例如:

class MyCustomClass: NSObject { ... }

@objc protocol X: NSObjectProtocol {
@objc dynamic var toBeObserved: MyCustomClass? { get }
}

class A: NSObject, X {
var toBeObserved: MyCustomClass? = MyCustomClass()
}

class B: NSObject {
@objc var x: X = A()

var token: NSKeyValueObservation?

func addObserver() {
token = observe(\.x.toBeObserved) { object, _ in
print(object)
}
}
}

关于Swift KVO 在符合协议(protocol)的对象上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56548323/

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