为什么我的iCloud KVS Observer无法正常工作

时间:2019-05-26 19:26:59

标签: swift icloud key-value-observing nsubiquitouskeyvaluestore

在我的应用中,我实现了一个Preferences类,看起来像这样。

public class Preferences: Codable {
    public static var sharedPreferences: Preferences = {
        let preferences = Preferences()

        return preferences
    }()

    public class func shared() -> Preferences {
        return sharedPreferences
    }

    private let cloud: NSUbiquitousKeyValueStore = NSUbiquitousKeyValueStore.default

    public init () {
        NotificationCenter.default.addObserver(self, selector: #selector(keysDidChangeOnCloud(notification:)),
                                               name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
                                               object: nil)
        self.cloud.synchronize()
    }

    @objc func keysDidChangeOnCloud(notification: Notification) {
        print("CLOUD CHANGED")
    }
}

我发现键值存储发生了变化。尽管print()从未执行过。知道为什么吗?

1 个答案:

答案 0 :(得分:0)

我相信您需要像这样观察NSUbiquitousKeyValueStore.default对象:

NotificationCenter.default.addObserver(self, selector: #selector(keysDidChangeOnCloud(notification:)),
                                           name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
                                           object: NSUbiquitousKeyValueStore.default)