问题描述
我正在重写应用程序的各个部分,并找到以下代码:
I'm rewriting parts of an app, and found this code:
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
计划已弃用.这是用代码编写的:
When CMD-clicking the line defaults.synchronize()
I see that synchronize
is planned deprecated. This is written in the code:
/*!
-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
*/
据我所知,我的用法符合第二种描述:在写入后同步 以便通知其他人.
As far as I can interpret, the usage in my case fits the second description: synchronizing after writing, in order to notify others.
它建议使用KVO进行排卵,但是如何呢?当我搜索此内容时,我发现了一堆稍旧的Objective-C示例.遵守UserDefaults的最佳做法是什么?
It suggests using KVO to ovserve, but how? When I search for this, I find a bunch of slightly older Objective-C-examples. What is the best practice for observing UserDefaults?
推荐答案
从iOS 11 + Swift 4开始,推荐的方式(根据 SwiftLint )正在使用基于块的KVO API.
As of iOS 11 + Swift 4, the recommended way (according to SwiftLint) is using the block-based KVO API.
示例:
假设我在用户默认值中存储了一个整数值,它称为greetingsCount
.
Let's say I have an integer value stored in my user defaults and it's called greetingsCount
.
首先,我需要扩展UserDefaults
:
extension UserDefaults {
@objc dynamic var greetingsCount: Int {
return integer(forKey: "greetingsCount")
}
}
这使我们以后可以定义观察的关键路径,如下所示:
This allows us to later on define the key path for observing, like this:
var observer: NSKeyValueObservation?
init() {
observer = UserDefaults.standard.observe(\.greetingsCount, options: [.initial, .new], changeHandler: { (defaults, change) in
// your change logic here
})
}
永远不要忘记清理:
deinit {
observer?.invalidate()
}
这篇关于如何在Swift中将KVO用于UserDefaults?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!