如何删除所有UserDefaults数据? -斯威夫特 [英] How to remove all UserDefaults data ? - Swift
问题描述
我有以下代码可从应用程序中删除所有UserDefaults
数据:
I have this code to remove all UserDefaults
data from the app:
let domain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: domain)
print(Array(UserDefaults.standard.dictionaryRepresentation().keys).count)
但是我从打印行得到了10
.是不是0
?
But I got 10
from the print line. Shouldn't it be 0
?
推荐答案
问题是您在清除UserDefaults内容后立即打印它们,但没有手动同步它们.
The problem is you are printing the UserDefaults contents, right after clearing them, but you are not manually synchronizing them.
let domain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: domain)
UserDefaults.standard.synchronize()
print(Array(UserDefaults.standard.dictionaryRepresentation().keys).count)
这应该可以解决问题.
现在您通常不需要手动调用synchronize
,因为系统会定期自动同步userDefaults,但是如果您需要立即推送更改,则需要通过synchronize
调用强制进行更新.
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.
因为此方法会定期自动调用,所以仅当您无法等待自动同步(例如,如果您的应用程序即将退出)或您想要将用户默认值更新为当前值时,才使用此方法.磁盘,即使您没有进行任何更改.
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.
这篇关于如何删除所有UserDefaults数据? -斯威夫特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!