ich Teile einer App Umschreiben und fand diesen Code:Wie verwendet man KVO für UserDefaults in Swift?
fileprivate let defaults = UserDefaults.standard
func storeValue(_ value: AnyObject, forKey key:String) {
defaults.set(value, forKey: key)
defaults.synchronize()
NotificationCenter.default.post(name: Notification.Name(rawValue: "persistanceServiceValueChangedNotification"), object: key)
}
func getValueForKey(_ key:String, defaultValue:AnyObject? = nil) -> AnyObject? {
return defaults.object(forKey: key) as AnyObject? ?? defaultValue
}
Wenn CMD-Klick auf die Linie defaults.synchronize()
ich sehe, dass synchronize
veraltet ist geplant. Dies wird in dem Code geschrieben:
/*!
-synchronize is deprecated and will be marked with the NS_DEPRECATED macro in a future release.
-synchronize blocks the calling thread until all in-progress set operations have completed. This is no longer necessary. Replacements for previous uses of -synchronize depend on what the intent of calling synchronize was. If you synchronized...
- ...before reading in order to fetch updated values: remove the synchronize call
- ...after writing in order to notify another program to read: the other program can use KVO to observe the default without needing to notify
- ...before exiting in a non-app (command line tool, agent, or daemon) process: call CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication)
- ...for any other reason: remove the synchronize call
*/
Soweit ich interpretieren kann, die Verwendung in meinem Fall paßt die zweite Beschreibung: nach Schreiben synchronisieren, um andere zu informieren.
Es schlägt vor KVO zu verwenden, aber wie? Wenn ich danach suche, finde ich ein paar etwas ältere Objective-C-Beispiele. Was ist die beste Vorgehensweise zum Beobachten von UserDefaults?
http://Stackoverflow.com/a/28744491/1419216 vielleicht, was Sie suchen. –
können Sie einen Beobachter für 'UserDefaults.didChangeNotification' hinzufügen –