我正在重写应用程序的各个部分,并找到以下代码:
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
}
当CMD单击
defaults.synchronize()
行时,我看到synchronize
计划已弃用。这是用代码编写的:/*!
-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
*/
据我所能解释的,我的用法符合第二种描述:写后同步,以便通知其他人。
它建议使用KVO进行观察,但是如何?当我搜索此内容时,我发现了一堆稍旧的Objective-C示例。遵守UserDefaults的最佳做法是什么?
最佳答案
从iOS 11 + Swift 4开始,推荐的方式(根据SwiftLint)是使用基于块的KVO API。
示例:
假设我有一个存储在用户默认值中的整数值,它称为greetingsCount
。
首先,我需要扩展UserDefaults
:
extension UserDefaults {
@objc dynamic var greetingsCount: Int {
return integer(forKey: "greetingsCount")
}
}
这使我们以后可以定义观察的关键路径,如下所示:
var observer: NSKeyValueObservation?
init() {
observer = UserDefaults.standard.observe(\.greetingsCount, options: [.initial, .new], changeHandler: { (defaults, change) in
// your change logic here
})
}
永远不要忘记清理:
deinit {
observer?.invalidate()
}
关于ios - 如何在Swift中将KVO用于UserDefaults?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43963220/