Userdefaults clear in entire project in swift

The UserDefaults
object, formerly known as NSUserDefaults
, is exceptionally useful for storing small pieces of data in your app. You use it to save your app user’s settings, set some “flags”, or simply use it as a tiny data store.
But as a developer, we might use Userdefaults in our apps at some point in time for storing some basic configuration or settings in the app. Like store user login credential and flags. But as the project gets complex, things can get pretty tough. Especially, when you want to clear all the UserDefaults values from the app. Well, we can use the removeObject
method to remove the value for a particular key. Yes, that’s good but it’s time consuming.
UserDefaults.standard.removeObject(forKey: "is_app_launched")
These can quickly mount up and you’ll typically end up with something like this in your project. The problem with something like this is that you have to remember to go and add an extra removeObjectForKey whenever you add a new setting and this can be easily forgotten and lead to settings being shared between different user accounts. some time I face vast number of keys, and we want to clear them all? Like 10 or 20 keys? If we try to clear all the keys using the removeObject
method, we might miss clearing some values, and the code becomes complex.
We don’t want to do that. So is there a better way? Yes, there is.
if let bundleID = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: bundleID)
}
This will clear all of the NSUserDefaults that have been set by your code leaving you with a fresh slate just as if the app had been deleted and reinstalled. You don’t need to update your logout method whenever a new setting gets added and you can be sure that everything is being reset in full.
We can wrap the API in the UserDefaults extension to use it convenient.
extension UserDefaults {
static func resetDefaults() {
if let bundleID = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: bundleID)
}
}
}
few people have asked why I perform synchronize.
UserDefaults.standardUserDefaults().synchronize() OR UserDefaults.synchronize()
Watch extensions, widgets, and keyboards that can all access a shared NSUserDefaults, I find it is always best to perform a sync (which ensures the data is written to disk immediately) as then none of the other aspects of your app or extensions will access invalid data. It doesn’t add any significant performance overhead in my experience but can save you from embarrassing bugs.
For Further Reading
Wait for my next block I coming soon.