How to delete a user default value in NSUserDefaults?
IphoneCocoa TouchUikitIphone Problem Overview
I.e., my app sets some standard default values at the beginning. Then those values may get overridden by the user. And when the user messes things up, I want to set those settings back to my app default values. As I understand it, the app defaults are a different dictionary than the user defaults, and the user defaults just override those app defaults. But I haven't seen methods for deleting the user defaults. Any idea?
Iphone Solutions
Solution 1 - Iphone
Try removeObjectForKey
-- that should give you the ability to remove a preference.
Solution 2 - Iphone
Use this code
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"MyKey"];
dont forget to synchronize if you want to save immediately
[[NSUserDefaults standardUserDefaults] synchronize];
NSUserDefaults Class Reference
synchronize - This method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.
Swift 5:
UserDefaults.standard.removeObject(forKey: "MyKey")
UserDefaults.standard.synchronize()
Solution 3 - Iphone
NSUserDefaults * removeUD = [NSUserDefaults standardUserDefaults];
[removeUD removeObjectForKey:@"shoping"];
[[NSUserDefaults standardUserDefaults]synchronize ];
Solution 4 - Iphone
Swift version for easy copy pasting:
var idForUserDefaults = "somestupidtext"
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.removeObjectForKey(idForUserDefaults)
userDefaults.synchronize()
or
NSUserDefaults.standardUserDefaults().removeObjectForKey("somestupidtext")
NSUserDefaults.standardUserDefaults().synchronize()
Solution 5 - Iphone
To remove a specific KEY value:
Swift 3+
UserDefaults.standard.removeObject(forKey: "KEY")
Obj-C
[[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)
}
Solution 6 - Iphone
Updated for Swift 3.0 code:
UserDefaults.standard.removeObject(forKey: "YOURKEY")
Solution 7 - Iphone
In Swift 4
UserDefaults.standard.removeObject(forKey: "your_key")
UserDefaults.standard.synchronize()
Solution 8 - Iphone
Swift way
UserDefaults.standard.removeObject(forKey: "aKey")
UserDefaults.standard.synchronize()