ios 如何删除所有 UserDefaults 数据?- 斯威夫特
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43402032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove all UserDefaults data ? - Swift
提问by Zizoo
I have this code to remove all UserDefaults
data from the app:
我有这个代码UserDefaults
从应用程序中删除所有数据:
let domain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: domain)
print(Array(UserDefaults.standard.dictionaryRepresentation().keys).count)
But I got 10
from the print line. Shouldn't it be 0
?
但我是10
从印刷线得到的。不应该0
吗?
回答by Lefteris
The problem is you are printing the UserDefaults contents, right after clearing them, but you are not manually synchronizing them.
问题是您正在清除 UserDefaults 内容后立即打印它们,但您没有手动同步它们。
let domain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: domain)
UserDefaults.standard.synchronize()
print(Array(UserDefaults.standard.dictionaryRepresentation().keys).count)
This should do the trick.
这应该可以解决问题。
Now you don't normally need to call synchronize
manually, as the system does periodically synch the userDefaults automatically, but if you need to push the changes immediately, then you need to force update via the synchronize
call.
现在您通常不需要synchronize
手动调用,因为系统会定期自动同步 userDefaults,但是如果您需要立即推送更改,则需要通过synchronize
调用强制更新。
Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.
由于此方法会定期自动调用,因此仅当您无法等待自动同步(例如,如果您的应用程序即将退出)或您想要更新用户默认为磁盘上的内容时才使用此方法,即使您没有进行任何更改。
回答by Ryan Poolos
This answer found here https://stackoverflow.com/a/6797133/563381but just incase here it is in Swift.
这个答案在这里找到https://stackoverflow.com/a/6797133/563381但只是以防万一它在 Swift 中。
func resetDefaults() {
let defaults = UserDefaults.standard
let dictionary = defaults.dictionaryRepresentation()
dictionary.keys.forEach { key in
defaults.removeObject(forKey: key)
}
}