Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to clear all NSUserDefaults values in objective-C? [duplicate]

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?

like image 972
New iOS Dev Avatar asked Apr 09 '15 10:04

New iOS Dev


People also ask

How do I delete data from UserDefaults?

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.

How do you check if NSUserDefaults is empty in Objective C?

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.

Where are the NSUserDefaults values stored?

All the contents saved by NSUserDefaults is saved inside a plist file that can be found under Library -> Preferences -> $AppBundleId.


1 Answers

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)
}
like image 161
Ajumal Avatar answered Oct 01 '22 05:10

Ajumal