ios - KVO 在单例属性(property)上?

标签 ios swift singleton key-value-observing kvc

大家好,我正在尝试在 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/

相关文章:

SwiftUI 分段选取器在单击时不会切换

ios - 从 UICollectionView 索引路径获取模型

c++ - 单例场景,重载不同参数的getInstance?

iOS/ swift 3.0 : how do you determine which rows are currently visible in a UITableView?

ios - 如何让选中的tableview单元格像Vine App一样没有颜色

ios - 对于iPad应用程序,如何构建一个应用程序以便可以在Production发布时看到它的最终速度?

ios - 从 UITableView 插入/删除单元格后的 IndexPath 错误

swift - 为什么我在 Cocoapods 中安装依赖后无法导入 swift 文件中的库?

android - 使用进度对话框作为单例类是好习惯吗

java - 单例类不起作用