0

在我的应用程序中,我实现了一个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()永远不会执行。知道为什么吗?

4

1 回答 1

0

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

NotificationCenter.default.addObserver(self, selector: #selector(keysDidChangeOnCloud(notification:)),
                                           name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
                                           object: NSUbiquitousKeyValueStore.default)
于 2019-05-28T13:16:21.113 回答