NSUserDefaults not being set - ios

This is my code in AppDelegate.m -didFinishLaunchingWithOptions:
// set color scheme
SingletonColorScheme *colorScheme = [SingletonColorScheme sharedColorScheme]; // initialize
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if(colorScheme.colorScheme == nil)
[defaults setObject:#"Saori" forKey:#"colorScheme"];
else
[defaults setObject:colorScheme.colorScheme forKey:#"colorScheme"];
[defaults synchronize]; // write them to disk
colorScheme.colorScheme = [defaults objectForKey:#"colorScheme"]; // set the singleton
NSLog(#"\n\nAppDelegate - colorScheme: %#\ndefault: %#\n\n", colorScheme.colorScheme, [[NSUserDefaults standardUserDefaults] stringForKey:#"colorScheme"]);
The NSLog shows this:
AppDelegate - colorScheme:
default: (null)
I know now that the code is not correct, but for the life of me, I don't see what's wrong. I would appreciate some help fixing this! :D
SD
UPDATED: changed key for NSLog

stringForKey:#"Saori"
should be
stringForKey:#"colorScheme"
-- you want to get the object for the key that you used previously.

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.

standardUserDefaults does not save boolean values

I have exhausted all my resources. The very simple process of storing a boolean value in standardUserDefaults simply does not work for me. Here's my test code:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:true forKey:#"BoolKey"];
[defaults setObject:#"Hello!!!" forKey:#"StrKey"];
[defaults synchronize];
BOOL b = [defaults boolForKey:#"BoolKey"]; // b equals NO
NSString *s = [defaults stringForKey:#"StrKey"]; // s equals "Hello!!!"
I can't understand why strings are stored fine, while booleans are not. Does anyone have any idea? I'm using XCode 6.0.1 (6A317).
Update: I found that changing the KeyName actually solved my problem. My boolean key was named LoginOK. I changed it to CredentialsStored, and now it loads correctly. Weird though...
I copy pasted your code and executed
Have look to bottom right in console
BOOL returned YES
This issue has nothing to do with Xcode 6.0.1 (6A137). Your code is correct. I believe there could be an error at when you are calling or executing these commands. You should try and debug, start with a simple example and NSlog the values. Click on your iOS Simulator >> Reset Contents and Settings and try.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:true forKey:#"BoolKey"];
[defaults setObject:#"Hello!!!" forKey:#"StrKey"];
[defaults synchronize];
BOOL b = [defaults boolForKey:#"BoolKey"];
NSLog(#"%d",b);
NSString *s = [defaults stringForKey:#"StrKey"];
NSLog(#"%#",s);

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

load/save settings in iOS

I have the following two procedures defined in my AppDelegate. saveSettings and loadSettings. I am calling my loadSettings procedure in the AppDidFinishLaunching method, and I am calling the saveSettings procedure in my settings view, once the save button is clicked.
Both methods seem to be called at the right time, the right number of times (once), and using the correct data. my settings object gets the right data, but the data does not seem to be actually saving. When I run the load code, my resulting variables are coming back empty (not nil).
I tried putting the same loading code in a different view and it works fine, but for some reason, I am not getting results in my appDelegate.
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[window addSubview:navigationController.view];
[window makeKeyAndVisible];
[self loadSettings];
[self setDefaults];
}
-(void)loadSettings{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
settings.masterLocation = [prefs objectForKey:#"masterLocation"];
settings.masterPort = [prefs objectForKey:#"masterPort"];
settings.userName = [prefs objectForKey:#"userName"];
settings.passWord = [prefs objectForKey:#"passWord"];
settings.autoLogin=[prefs objectForKey:#"autoLogin"];
if (settings.autoLogin == nil)
settings.autoLogin=#"N";
}
-(void)saveSettings:(SharedData *)d{
settings=d;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:settings.masterLocation forKey:#"masterLocation"];
[prefs setObject:settings.masterPort forKey:#"masterPort"];
[prefs setObject:settings.userName forKey:#"userName"];
[prefs setObject:settings.passWord forKey:#"passWord"];
[prefs setObject:settings.autoLogin forKey:#"autoLogin"];
}
Doh.
In saveSettings, I was missing my [prefs synchronize];
to make it sample:
//Writing
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:#"anInt"];
[[NSUserDefaults standardUserDefaults] setDouble:1.2 forKey:#"aDouble"];
[[NSUserDefaults standardUserDefaults] setString:#"aString" forKey:#"aString"];
[[NSUserDefaults standardUserDefaults] synchronize];
//Reading:
int i = [[NSUserDefaults standardUserDefaults] integerForKey:#"anInt"]

Resources