大家好,我正在尝试在 Singleton 类中的一个字符串属性上实现 KVO。我目前在尝试添加观察者时遇到了一些错误,希望有人能告诉我我做错了什么。 下面显示了我的单例类。
class User: NSObject {
static let currentUser = User()
private override init() {}
var pictureString: String?
}
在单独的 ViewController 的 viewDidLoad 中,我尝试像这样向 pictureString 变量添加观察者。
self.addObserver(self, forKeyPath: #keyPath(User.currentUser.pictureString), options: [.old, .new, .initial], context: nil)
我现在正在处理的问题是它声明 currentUser 不符合 KVC。我目前遇到以下错误。
addObserver: forKeyPath:@"currentUser.pictureString" options:7 context:0x0] was sent to an object that is not KVC-compliant for the "currentUser" property.'
如果有任何帮助,我将不胜感激。
最佳答案
参见 this answer :
As for now, Swift cannot have observable class properties.
如果你真的想使用单例,你可以将它转换为具有普通属性的非静态单例,然后也可以是 KVO ......像这样:
class UserManager: NSObject {
private override init() {}
static var instance = UserManager()
var currentUser = User()
}
class User: NSObject {
dynamic var pictureString: String?
}
注意变量声明中的 dynamic
关键字——这是使 KVO 在 Swift 中工作所必需的(动态调度在 here 中解释)。
然后在您的 VC 的 viewDidLoad
中,您可以注册更改:
UserManager.instance.addObserver(self, forKeyPath: #keyPath(UserManager.currentUser.pictureString), options: [.old, .new, .initial], context: nil)
关于ios - KVO 在单例属性(property)上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44275632/