How to remove all UserDefaults data ? - Swift [duplicate]

梦想与她 提交于 2019-12-20 11:03:24

问题


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)

But I got 10 from the print line. Shouldn't it be 0?


回答1:


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)

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.

The documentation states this

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.




回答2:


This answer found here https://stackoverflow.com/a/6797133/563381 but just incase here it is in Swift.

func resetDefaults() {
    let defaults = UserDefaults.standard
    let dictionary = defaults.dictionaryRepresentation()
    dictionary.keys.forEach { key in
        defaults.removeObject(forKey: key)
    }
}


来源:https://stackoverflow.com/questions/43402032/how-to-remove-all-userdefaults-data-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!