How to remove user default value in NSUserDefaults?

Ie, my application sets some standard defaults at the beginning. Then these values ​​can be overridden by the user. And when the user messed up everything, I want these parameters to return to the default values ​​for my application. As far as I understand, application defaults are different vocabulary words than user-defined defaults, and user-defined defaults simply override these application defaults. But I have not seen methods to remove user defaults. Any idea?

+62
iphone cocoa-touch uikit
Aug 27 '09 at 16:53
source share
6 answers

Try removeObjectForKey - this should give you the opportunity to remove the preference.

+119
Aug 27 '09 at 16:57
source share

Use this code

 [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"MyKey"]; 

don't forget to sync if you want to save immediately

 [[NSUserDefaults standardUserDefaults] synchronize]; 

Reference to the NSUserDefaults Class

synchronize . This method is automatically called at regular intervals, use this method only if you cannot wait for automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults on disk, even if you have not made any changes.

+84
May 15 '12 at 12:22
source share

Quick version for easy copying:

 var idForUserDefaults = "somestupidtext" var userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.removeObjectForKey(idForUserDefaults) userDefaults.synchronize() 

or

 NSUserDefaults.standardUserDefaults().removeObjectForKey("somestupidtext") NSUserDefaults.standardUserDefaults().synchronize() 
+8
Mar 23 '15 at 12:44
source share
 NSUserDefaults * removeUD = [NSUserDefaults standardUserDefaults]; [removeUD removeObjectForKey:@"shoping"]; [[NSUserDefaults standardUserDefaults]synchronize ]; 
+7
Feb 26 '14 at 10:22
source share

Updated for Swift 3.0:

UserDefaults.standard.remove(forKey: "YOURKEY")

+3
Oct 14 '16 at 3:36
source share

To remove a specific KEY value:

 [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"KEY"]; [[NSUserDefaults standardUserDefaults] synchronize]; 

If you need to reset UserDefaults / Clear All datas:

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

Swift 3:

 if let bundle = Bundle.main.bundleIdentifier { UserDefaults.standard.removePersistentDomain(forName: bundle) } 
+3
Dec 08 '16 at 9:52
source share



All Articles