How to set initial values for NSUserDefault Keys? - ios

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

Related

NSUserDefault is clearing once the application kills

For Saving the data
NSString *balSnapTokenFromResponce;
balSnapTokenFromResponce = #"456294797493749873";
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:balSnapTokenFromResponce forKey:#"Token"];
[defaults synchronize];
For Retreiving the Data
[[NSUserDefaults standardUserDefaults] stringForKey:#"Token"]
This, as shown, makes no sense:
[[NSUserDefaults standardUserDefaults] stringForKey:#"Token"]
You must do something with the return value:
NSString *balSnapTokenFromResponce = [[NSUserDefaults standardUserDefaults] stringForKey:#"Token"];
Perhaps you are, but that's not clear from your question. Because otherwise the code you've posted should work, assuming it's getting called.

`[NSUserDefaults standardUserDefaults]` returns nil

I want to save some user preferences, but
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
just returns nil.
iOS-Developper Library says, that this should return the existing shared defaults object or create one if none exists... What am I missing?
I also use Appirater and there all this stuff seems also not to work...
This code gets called when the user pushes a button...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int index = ([defaults integerForKey:#"BackgroundColorSpecifier"]+ 1)%self.backgroundColors.count;
[defaults setInteger:index forKey:#"BackgroundColorSpecifier"];
[defaults synchronize];
This gets called in application: didFinishLaunchingWithOptions:
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
[standardDefaults registerDefaults:#{#"BackgroundColorSpecifier": #0}];
[standardDefaults synchronize];
When I debug this code snippets the green "position-indicator" jumps around in a very strange manner...
I don't have any clue, whats going on... Please help!
This is far more likely to be a problem with the debugger than anything else, particularly with your other issues. I've seen similar things in my own projects but don't have a reliable way of clearing it out other than the usual restart / clean options.
NSLogs will usually give more consistent results than the debugger if the debugger is having an off day.
NSUserDefaults isn't broken. We'd have heard about it by now.
you can use this function to log you userDefaults dic
- (void)logCache
{
NSDictionary * dic = [[NSBundle mainBundle] infoDictionary];
NSString *bundleId = [dic objectForKey: #"CFBundleIdentifier"];
NSUserDefaults *appUserDefaults = [[NSUserDefaults alloc] init];
NSDictionary *cacheDic = [appUserDefaults persistentDomainForName: bundleId];
NsLog(#"cacheDic::%#",cacheDic);
}

NSUserDefaults doesn't save my values

I use this code to save:
[[NSUserDefaults standardUserDefaults] setValue:#"vruch" forKey:#"nastoikaIP"];
[[NSUserDefaults standardUserDefaults] synchronize];
and this code to load:
NSString* automanual = [[NSUserDefaults standardUserDefaults]
valueForKey:#"nastroikaIP"];
if ([automanual isEqualToString:#"vruch"]) {
autovruch.selectedSegmentIndex = 1;
[self obnovittext];
}
You should not use the method setValue: (from the NSKeyValueCoding protocol) but setObject: (from the NSUserDefaults class) to store the string.
[[NSUserDefaults standardUserDefaults] setObject:#"vruch" forKey:#"nastroikaIP"];
[[NSUserDefaults standardUserDefaults] synchronize];
You can retrieve the string using the method stringForKey:
NSString* automanual = [[NSUserDefaults standardUserDefaults] stringForKey:#"nastroikaIP"];
Finally, note that it is generally better to define constants for the keys you use in NSUserDefaults to avoid any mistyping errors, which may be hard to debug when they happen.
Edit
It looks like you already did a mistyping error nastoikaIP != nastroikaIP. Notice the missing/extra r letter.
Your saving a string so you need to setObject rather than setValue
[[NSUserDefaults standardUserDefaults] setObject:#"vruch" forKey:#"nastoikaIP"];
[[NSUserDefaults standardUserDefaults] synchronize];
and change it for the loading aswell
NSString* automanual = [[NSUserDefaults standardUserDefaults] objectForKey:#"nastroikaIP"];
if ([automanual isEqualToString:#"vruch"]) {
autovruch.selectedSegmentIndex = 1;
[self obnovittext];
}

NSUserDefaults Contains Value Or Not?

How to know whether NSUserDefaults contains any value?How to check whether its empty?
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.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSObject * object = [prefs objectForKey:#"your_particular_key"];
if(object != nil){
//object is there
}
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *string = [data objectForKey:#"yourKey"];
if(string==nil)
NSlog(#"nil")
Take a look at NSUserDefault documentation
// For saving the values
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
// saving an NSString
[userDefaults setObject:#"Ttest" forKey:#"key"];
// --- For Retrieving
NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [userDefaults stringForKey:#"key"];
To check whether a specific value is set or not, no matter of its location (global or application's), check the returned value of -[NSUserDefaults objectForKey:]
id obj = [[NSUserDefaults standardUserDefaults] objectForKey:#"My-Key-Name"];
if (obj != nil) {...}
To check if the application (bundle) has any settings stored in user defaults:
NSUserDefaults* sdu = [NSUserDefaults standardUserDefaults];
NSString* bundleId = [[NSBundle mainBundle] bundleIdentifier];
NSDictionary* mainBundleSettings = [sdu persistentDomainForName:bundleId];
NSLog(#"%#", mainBundleSettings);
If you are interested in all possible values for which -[NSUserDefaults objectForKey:] will return something, including system global settings, simply call
NSDictionary* allPossibleSettings = [sdu dictionaryRepresentation];
NSUserDefaults is never empty. It combines global settings, bundle's settings, temporary data and maybe something else. For example, if you call:
[[NSUserDefaults standardUserDefaults] objectForKey:#"NSBoldSystemFont"]
you will get the #"LucidaGrande-Bold" string value which will be taken from global settings, even when your application has never set this value.

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