I am using NSUserDefaults lots of time in my app to store some values, but on "refresh button" i want to clear all stored values, Is there any way to clear all NSUserDefaults values?
To remove a key-value pair from the user's defaults database, you need to invoke removeObject(forKey:) on the UserDefaults instance. Let's update the previous example. The output in the console confirms that the removeObject(forKey:) method works as advertised.
There isn't a way to check whether an object within NSUserDefaults is empty or not. However, you can check whether a value for particular key is nil or not.
All the contents saved by NSUserDefaults is saved inside a plist file that can be found under Library -> Preferences -> $AppBundleId.
You can remove all stored value using below code see here for more details
- (void)removeUserDefaults
{
NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary * dict = [userDefaults dictionaryRepresentation];
for (id key in dict) {
[userDefaults removeObjectForKey:key];
}
[userDefaults synchronize];
}
Or in shortest way
[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];
Swift
let defaults = UserDefaults.standard
defaults.dictionaryRepresentation().keys.forEach { (key) in
defaults.removeObject(forKey: key)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With