在我的应用中,我实现了一个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()
从未执行过。知道为什么吗?
答案 0 :(得分:0)
我相信您需要像这样观察NSUbiquitousKeyValueStore.default对象:
NotificationCenter.default.addObserver(self, selector: #selector(keysDidChangeOnCloud(notification:)),
name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
object: NSUbiquitousKeyValueStore.default)