How to delete all UserDefaults data? - fast

I have this code to delete all UserDefaults data from the application:

 let domain = Bundle.main.bundleIdentifier! UserDefaults.standard.removePersistentDomain(forName: domain) print(Array(UserDefaults.standard.dictionaryRepresentation().keys).count) 

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

+5
source share
2 answers

The problem is that you print the contents of UserDefaults immediately after they are cleared, but you do not synchronize them manually.

 let domain = Bundle.main.bundleIdentifier! UserDefaults.standard.removePersistentDomain(forName: domain) UserDefaults.standard.synchronize() print(Array(UserDefaults.standard.dictionaryRepresentation().keys).count) 

That should do the trick.

Now you usually donโ€™t need to call synchronize manually, since the system automatically synchronizes userDefaults, but if you need to push the changes immediately, you need to force update using the synchronize call.

The documentation states this

Since this method is automatically called at periodic intervals, use this method only if you cannot wait for automatic synchronization (for example, if your application is about to exit) or if you want to update the user's default disk settings, even if you have not made any changes.

+21
source

This answer is found here fooobar.com/questions/17956 / ... , but just here it is in Swift.

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

Source: https://habr.com/ru/post/1266715/


All Articles