私は、アプリの一部を書き換えて、このコードを見つけています:SwiftのUserDefaultsにKVOを使用するには?
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
}
私はsynchronize
は廃止予定されていることがわかりdefaults.synchronize()
ラインをCMD-クリックします。これは、コードで書かれている:他のユーザーに通知するために、書き込み後を同期:
/*!
-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
*/
は、私の知る限りが解釈できるように、私の場合での使用は、第二の記述に適合します。
これはovserveにKVOを使用することを示唆していますが、どのようにですか?私がこれを検索すると、少し古いObjective-C-examplesの束が見つかります。 UserDefaultsを観察するためのベストプラクティスは何ですか?
http://stackoverflow.com/a/28744491/1419216多分あなたが探しているもの。 –
あなたは 'UserDefaults.didChangeNotification'にオブザーバーを追加できます –