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

This question already has answers here:
Clearing NSUserDefaults
(15 answers)
Closed 7 years ago.
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?

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)
}

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];
}

Related

How to clear NSUserDefaults Data?

When I choose a language from language selection list in my app then it shows that language which I selected previously. If I clear the app from my simulator stack or clear it from xcode then run the project, after that it goes ok, and if I want to change the language again then I faced same problem. My code is given below:
- (IBAction)English:(id)sender {
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
[userDefault setObject:[NSArray arrayWithObjects:#"en", nil] forKey:#"AppleLanguages"];
[userDefault synchronize];
ChooseItemVC *civc = (ChooseItemVC*)[self.storyboard instantiateViewControllerWithIdentifier:#"ChooseItemVC"];
[self.navigationController pushViewController:civc animated:YES];
}
Another language selection code:
- (IBAction)Arabic:(id)sender {
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
[userDefault setObject:[NSArray arrayWithObjects:#"ar", nil] forKey:#"AppleLanguages"];
[userDefault synchronize];
ChooseItemVC *civc = (ChooseItemVC*)[self.storyboard instantiateViewControllerWithIdentifier:#"ChooseItemVC"];
[self.navigationController pushViewController:civc animated:YES];
}
The best way to remove all user default vlaues are as follows :
Swift code:
UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)
UserDefaults.standard.synchronize()
Objective C
NSString *strIdentifier = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:strIdentifier];;
[[NSUserDefaults standardUserDefaults] synchronize];
Use following code to remove all existing data in user defaults, i am posting swift code, convert this to objective-c.
if let bundleID = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: bundleID)
}
To remove use this
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
[[NSUserDefaults standardUserDefaults] synchronize];
To remove you data from NSUserDefaults
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"AppleLanguages"];
For remove data from NSUserDefaults Try this:
NSString *AppDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:AppDomain];

Objective-C : Can't set NSMutableDictionary from NSUserDefaults

I'm trying to retrieve an NSDictionary that was saved to NSUserDefaults. When I log out what I'm trying to retrieve, it displays correctly:
NSLog(#"%#", [[[NSUserDefaults standardUserDefaults] dictionaryForKey:#"userdetails"] mutableCopy]);
However, when I try to assign to a variable, it returns as nil.
NSMutableDictionary *test123 = [[[NSUserDefaults standardUserDefaults] dictionaryForKey:#"userdetails"] mutableCopy];
Any idea why?
Check with my working code,
Save like this,
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:yourMutableDictionary];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"currentUser"];
[[NSUserDefaults standardUserDefaults]synchronize];
Get dictionary ,
NSData *dictionaryData = [[NSUserDefaults standardUserDefaults] objectForKey:#"currentUser"];
NSDictionary *tempDict = [NSKeyedUnarchiver unarchiveObjectWithData:dictionaryData];
Maybe you can try it use the following code:
[[NSUserDefaults standardUserDefaults] setObject:(NSDictionary *)yourDictionary forKey:yourkey];

App crashing during NSUserDefault data removal

When I call this function my app gets crash.
I got this error : [__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[1].
How i can resolve it please help if you know.
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
NSDictionary *dict = [defs dictionaryRepresentation];
for (id key in dict)
{
NSObject * object = [dict objectForKey:key];
if(object != nil)
{
[defs removeObjectForKey:key];
[defs synchronize];
}
}
Kindly use following code. It should help you
NSString *applicationDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:applicationDomain];
You can also use
NSDictionary *defaultsDictionary = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
for (NSString *key in [defaultsDictionary allKeys]) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}
[[NSUserDefaults standardUserDefaults] synchronize]; //outside loop.
NOTE: The crash which you are mentioning is regarding setValue ForKey in a Dictionary. Kindly user breakpoint and see where you are inserting nil value in Dictionary.
try adding the keys of the desired entries into NSArray inside the loop
then do removeObjectsForKeys:array outside the loop
It's preferable to not remove entries while enumerating inside a for loop
My solution for your question is
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
NSDictionary *dict = [userDefaults dictionaryRepresentation];
for (id key in dict) {
[dict removeObjectForKey:key];
}
[defs synchronize];

How to set initial values for NSUserDefault Keys?

I want to set some initial values for my NSUserDefault keys so that the first run of the app has some reasonable initial settings. I thought I ran across a simple way to do this in the app bundle .plist, but now I can't find it. Any ideas?
You should use the registerDefaults method of NSUserDefaults. Prepare a plist file in your bundle that contains the default preferences and then use that plist to register the defaults.
NSString *defaultPrefsFile = [[NSBundle mainBundle] pathForResource:#"defaultPrefs" ofType:#"plist"];
NSDictionary *defaultPreferences = [NSDictionary dictionaryWithContentsOfFile:defaultPrefsFile];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultPreferences];
You have to execute this code on every launch of your app. It will add these values to a separate domain in the user defaults hierarchy. Whenever your app's user defaults don't provide a value for a certain key, NSUserDefaults will fall back to this domain and retrieve the value from there.
If you have many default values, let use ola's answer, otherwise this is good for a few params
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults boolForKey:USERDEFAULT_IS_INITIALIZED]) {
[defaults setBool:YES forKey:USERDEFAULT_IS_INITIALIZED];
// Set initial values
...
[defaults synchronize];
}
if ([[[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys] containsObject:#"initialValuesHaveBeenWritten"])
{
[[NSUserDefaults standardUserDefaults] setValue:obj1 forKey:key1];
[[NSUserDefaults standardUserDefaults] setValue:obj2 forKey:key2];
[[NSUserDefaults standardUserDefaults] setValue:obj1 forKey:#"initialValuesHaveBeenWritten"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
NB: Not tested, done from memory
-(void) loadDef
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
_removeAd=[userDefaults boolForKey:SAVE_AD_STATUS];
NSString* strDefSetting=[userDefaults stringForKey:SAVE_STATUS_ADSETTING];
if(strDefSetting==nil
||[strDefSetting isEqualToString:#""]
)
{
strDefSetting=#"0.5";
}
_floatAdmob=strDefSetting.floatValue;//0.5;
}

How would I save a UIButton's properties and load with a button? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I save and load the alpha values of a UIButton in an app?
I would like to save the state of the UIButton (e.g. its alpha value and whether it is hidden or not) and this would then load up when the user quits and reloads the app.
I've tried some bits of code with NSUserDefaults but with no luck.
Could somebody help with some sample code so that I can save and load the button's state?
Thanks,
James
Related to Shaharyar's answer (i don't know how to comment):
in this case you need to use NSNumber.
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithFloat:SOME_FLOAT] forKey:KEY];
because float is not an object, but NSNumber is one.
EDITED:
1) To make sure your defaults are created after the application runs at first time:
in your AppDelegate's initialize-method:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:SOME_FLOAT], #"YOUR_KEY",
nil];
[defaults registerDefaults:appDefaults];
2) Updating defaults after:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setFloat:FLOAT_VALUE forKey:#"YOUR_KEY"];
[prefs synchronize];
3) Read defaults:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
float FLOAT_VALUE = [prefs floatForKey:#"YOUR_KEY"];
Can you post some of the code?
NSUserDefaults is the place to store such information..
Assumption:
Did you make a call to [NSUserDefaults synchronize] after setting the values?
Code:
// Setting a value
[[NSUserDefaults standardUserDefaults] setValue:VALUE forKey:KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
// Getting a value
NSString *var1 = [[NSUserDefaults standardUserDefaults] valueForKey:KEY];
In your case it would be:
// Setting a value
[[NSUserDefaults standardUserDefaults] setFloat:VALUE forKey:KEY];
[[NSUserDefaults standardUserDefaults] synchronize];

Resources