Delete all keys from a NSUserDefaults dictionary iOS

Viewed 65672

I use the NSUserDefaults dictionary to store basic information such as high scores etc so that when the user closes the app data is not lost. Anyways I use:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

to store data. If I wish to store a new high score for example then I would do:

[prefs setInteger:1023 forKey:@"highScore"];
[prefs synchronize];  //this is needed in case the app is closed. 

and later if I wish to retrieve the high score I would do:

[prefs integerForKey:@"highScore"];

anyways the point is that I store a lot of other things because the NSUserDefaults enable you to store booleans, integers, objects etc. what method would I have to execute to delete all keys so that NSUserDefaults becomes like the fist time I launch the app?

I am looking for something like:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs deleteAllKeysAndObjectsInTheDictionary];

or maybe there is a way of getting all keys and I have to loop through each object but I don't know how to remove them.

EDIT:

I have tried :

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[NSUserDefaults resetStandardUserDefaults];
[prefs synchronize];

and I still am able to retrieve a high score....

18 Answers

Simple Solution

Objective C:

NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

Swift 3.0 to Swift 5.0 :

if let appDomain = Bundle.main.bundleIdentifier {
    UserDefaults.standard.removePersistentDomain(forName: appDomain)
}

Swift
place in your logic

if let appDomain = Bundle.main.bundleIdentifier {
  UserDefaults.standard.removePersistentDomain(forName: appDomain)
}

I found it the most handy to place the code in an extension on UserDefaults.

Swift 5

extension UserDefaults {
    static func clear() {
        guard let domain = Bundle.main.bundleIdentifier else { return }
        UserDefaults.standard.removePersistentDomain(forName: domain)
        UserDefaults.standard.synchronize()
    }
}

Usage

UserDefaults.clear()

To remove all UserDefault value in swift (Latest syntax)

//remove UserDefaults
if let identifier = Bundle.main.bundleIdentifier {
  UserDefaults.standard.removePersistentDomain(forName: identifier)
  UserDefaults.standard.synchronize()
}

In Swift 5.0 below single line of code is enough.

UserDefaults.standard.dictionaryRepresentation().keys.forEach(defaults.removeObject(forKey:))

I use this:

UserDefaults.standard.removeAll()
Related