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?
Asked
Active
Viewed 1.1k times
2 Answers
14
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)
}

Ajumal
- 1,048
- 11
- 33
-
The single-line solution did not work for me. However, the removeUserDefaults() function did the job. – C1pher May 25 '17 at 23:22
5
You can clear your user defaults by using following statements -
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
You can call a selector on the refresh button and keep the above statements in it, as-
- (void) refreshUserDefaults
{
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
}

Sanjay Mohnani
- 5,947
- 30
- 46
-
Your second option isn't valid here and makes it seem you have misunderstood the question. This isn't what was being asked they specifically state that the `NSUserDefaults` to be cleared when pressing the reset button, how would pressing the reset button in there app make 2 happen? – Popeye Apr 09 '15 at 11:11
-