[[NSUserDefaults standardUserDefaults] setObject:datePicker.date forKey:#"birthDate"];
[[NSUserDefaults standardUserDefaults] setInteger:sexSegmented.selectedSegmentIndex forKey:#"sex"];
[[NSUserDefaults standardUserDefaults] synchronize];
This is the value that I am saving to userdefaults and from another class I want to call them.
NSDate *birthDate = [[NSUserDefaults standardUserDefaults] objectForKey:#"birthDate"];
NSInteger a=[[NSUserDefaults standardUserDefaults] integerForKey:#"sex"];
NSLog(#"%#",birthDate);
[datePicker setDate:birthDate animated:YES];
sexSegmented.selectedSegmentIndex=a;
This is the other class from where I am getting the saved values, but I can't see any value in birthDate. I want to take it and set the new datePicker to birthDate. Can anyone help me?
It's most likely a case of the interface outlet of datePicker not being connected properly. This would make datePicker nil and as a result you would end up storing nil in the user defaults.
You can validate this by doing
NSLog(#"%#", datePicker);
before your first snippet of code.
Related
I need to set a slider in preferences window of a cocoa application.
If I set the NSSlider in awakeFromNib like so
-(void)awakeFromNib{
[thresholdSlider setInValue:9];
}
the preference window updates with the value when opened.
Though, since it is a preference window, I need to register the Value with NSUserDefault, so when the application at launch would run :
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
[thresholdSlider setValue:[NSUserDefaults standardUserDefaults] forKey:kthresh];
NSLog( #"%#",[thresholdSlider objectValue]);
}
But I cant even set the slider value in the applicationDidFinishLaunching method
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
[thresholdSlider setIntValue:9];
NSLog( #ā%dā,[thresholdSlider intValue]);}
returns 0 and slider is set to minimum value(set in IB) in the preferences window.
Where can I call the [thresholdSlider setValue:[NSUserDefaults standardUserDefaults] forKey:kthresh]; to get the slider updated with the user value on last application quit?
The code edited according to Vadian proposition :
+(void)initialize{
NSDictionary *dicDefault = #{#"kthresh":#9};
[[NSUserDefaults standardUserDefaults]registerDefaults:dicDefault];}`
`- (void)applicationDidFinishLaunching:(NSNotification*)aNotification{
`//Preferences
NSInteger thresholdValue = [[NSUserDefaults standardUserDefaults] integerForKey:#"kthresh"];`
thresholdSlider.integerValue = thresholdValue;}`
`-(void)applicationWillTerminate:(NSNotification *)notification {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:thresholdSlider.integerValue forKey:#"kthresh"];
[defaults synchronize];}`
In AppDelegate as soon as possible register the key value pair with a default value. This value is always used if no custom value has been written to disk yet.
NSDictionary *defaultValues = #{#"kthresh" : #9};
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];
Then set the value of the slider wherever you want, consider the syntax
NSInteger thresholdValue = [[NSUserDefaults standardUserDefaults] integerForKey:#"kthresh"];
thresholdSlider.integerValue = thresholdValue;
To write the value to disk use this
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults] ;
[defaults setInteger:thresholdSlider.integerValue forKey:#"kthresh"];
[defaults synchronize];
Do not use setValue:forKey: and valueForKey: to talk to NSUserDefaults
Alternatively use Cocoa bindings and bind the key integerValue to the NSUserDefaultsController instance in Interface Builder.
[thresholdSlider setValue:[NSUserDefaults standardUserDefaults] forKey:kthresh];
should be
[thresholdSlider setObjectValue:[[NSUserDefaults standardUserDefaults] valueForKey:kthresh]];
I am using a lot NSUserDefaults and i want every time the app starts to remove them except two objects is this somehow possible?
Any help appreciated
I assume you know which two objects you want to keep? If that's the case use this code:
id obj1 = [[NSUserDefaults standardUserDefaults] objectForKey#"keyForObj1"];
id obj2 = [[NSUserDefaults standardUserDefaults] objectForKey#"keyForObj2"];
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
[[NSUserDefaults standardUserDefaults] setObject:obj1 forKey:#"keyForObj1"];
[[NSUserDefaults standardUserDefaults] setObject:obj2 forKey:#"keyForObj2"];
You would need to keep track of the keys yourself and remove the objects associated with them on launch. More importantly, though: why are you storing data in NSUserDefaults that you only want to persist through a single run of the app? That sort of data should probably be kept in memory.
You can save Those two items under separate a key and Add into the Code during ViewDidLoad.
Let me know the Actual Problem.
Maybe somebody will know, how to "tag" NSuserdefaults.
I have like 10 user defaults:
name
pin
etc...
I want to make another object, which would have the same defaults as the other ones (same variables but different values). Like a version, if object == 1 then load one userdefaults and if object == 0 another ones. But how to make it done?
Tried to make something like this
[NSUserDefaults setVersion:object.intValue];
But i guess this isn't the way to do it. So maybe anyone could help how to make it done?
To be more specific a simple example would help like how to do this:
Object (1 or 0)
[[NSuserDefaults standartUserDefaults] setObject: #"something"
forKey: #"Name"];
[[NSUserDefaults standartUserDefaults] synchronize];
NSString *name = [[NSUserDefaults standartUserDefaults] stringForKey:"#name"];
How to set and get this Name depending on Object value?
You could use persistent domains.
NSMutableDictionary *defaults = [[[NSUserDefaults standardUserDefaults] persistantDomainForName:#"aString"] mutableCopy];
// make changes to the dictionary here
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:#"aString"];
[[NSUserDefaults standardUserDefaults] setPersistantDomain:defaults forName:#"aString"];
Note that you'll need to be accessing all the defaults via the dictionary if you do this.
This is supposed to save the value of two UISwitches to NSUserDefaults and then set the switches on load based on the values saved to the defaults. I've been at this for hours but I can't seem to get it to work. Any help would be greatly appreciated.
The toggles are in a View that I'm using for settings. There are only two toggles, so I want to use NSUserDefaults. Toggles default to OFF. I want to toggle to ON and have that change be saved so that I can change the User experience based on the toggle's value. Then, when the User opens the settings again, I want them to display their current saved state.
I think that the value is being saved, but it is not being applied to the Switches when I reenter the Settings View.
- (IBAction)setBeadVibratorBySwitchState:(id)sender
{
if (setBeadVibrator.selected == YES) {
NSUserDefaults *beadSettings = [NSUserDefaults standardUserDefaults];
[beadSettings setBool:NO forKey:#"beadSwitchStatus"];
[beadSettings synchronize];
}
if (setBeadVibrator.selected == NO) {
NSUserDefaults *beadSettings = [NSUserDefaults standardUserDefaults];
[beadSettings setBool:YES forKey:#"beadSwitchStatus"];
[beadSettings synchronize];
}
NSLog(#"Bead Executed");
}
- (IBAction)setDecadeVibratorBySwitchState:(id)sender
{
if (setDecadeVibrator.selected == YES) {
NSUserDefaults *decadeSettings = [NSUserDefaults standardUserDefaults];
[decadeSettings setBool:NO forKey:#"decadeSwitchStatus"];
[decadeSettings synchronize];
}
if (setDecadeVibrator.selected == NO){
NSUserDefaults *decadeSettings = [NSUserDefaults standardUserDefaults];
[decadeSettings setBool:YES forKey:#"decadeSwitchStatus"];
[decadeSettings synchronize];
}
NSLog(#"Decade Executed");
}
- (void)viewDidLoad
{
[super viewDidLoad];
setBeadVibrator.selected = [[NSUserDefaults standardUserDefaults] boolForKey:#"beadSwitchStatus"];
setDecadeVibrator.selected = [[NSUserDefaults standardUserDefaults] boolForKey:#"decadeSwitchStatus"];
}
NSUserDefaults can only store objects of type NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. So, I suggest that you put the state of the switch in an NSString and put that string in the NSUserDefaults. Than when you retrieve the info from the NSUserDefaults, you can use an if statement to set the value of the boolean again.
If you are using UISwitch, you should set the on property, instead of selected.
setBeadVibrator.on = [[NSUserDefaults standardUserDefaults] boolForKey:#"beadSwitchStatus"];
setDecadeVibrator.on = [[NSUserDefaults standardUserDefaults] boolForKey:#"decadeSwitchStatus"];
see UISwitch Class Reference
I would suggest that you put the NSLog statements in the if-statements to see if they are really saved. If not, your UISwitches may not be configured properly with the UIControlEventValueChanged event.
You can read up more from Apple doc. Here is a very detailed website on using UISwitches.
I trying to store some settings in NSUserDefaults, but It seems that the app won't store the setBool values.
This works:
[[NSUserDefaults standardUserDefaults] setValue: #"hello" forKey: #"test"];
[[NSUserDefaults standardUserDefaults] synchronize];
When I terminate the app and restart it, the value have been saved. However, when I do this:
[[NSUserDefaults standardUserDefaults] setBool: YES forKey: #"test"];
[[NSUserDefaults standardUserDefaults] synchronize];
It won't save after I close the app and restart it.
Should I file a bug report, or is there something I'm missing here?
Thanks
Edit:
I figure what I did wrong. In AppDelegate, I wanted to check if the boolForKey was set, and it it wasn't I did this:
if (![defaults boolForKey: #"test123"])
[defaults setBool: YES forKey: #"test123"];
... however, when it comes to boolWithKey, the "!" just check if the bool is YES or NO, not if its nil.
How can you be sure its not working? I tried your code and it works for me. Are you sure you are reading the Boolean in the correct way AFTER you write it?
This code SHOULD work:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:NO forKey:#"test"];
[defaults synchronize];
BOOL myBool = [defaults boolForKey:#"test"];
I had the same problem by having the following code in my AppDelegate to keep track of whether the user had seen a particular viewController to display a walkthrough, and then setting this Bool to NO after the user had seen it.
if (![standardUserDefaults boolForKey:#"firstViewOfVC"]) {
[standardUserDefaults setBool:YES forKey:#"firstViewOfVC"];
}
But then when you set it to NO later on and check if it "exists", you are actually seeing the NO boolean value and setting it back to yes. The quick fix is just to store the boolean value in an NSNumber object so that you can check for it's existence, independent of its value being YES or NO. See below:
if (![standardUserDefaults objectForKey:#"firstViewOfVC"]){
[standardUserDefaults setValue:[NSNumber numberWithBool:YES] forKey:#"firstViewOfVC"];
}
I had the exact same problem. Everything EXCEPT BOOLs were persisting correctly; but i was using some old coding styles from ios 3. recoded this way, everything works.
If anybody else is using old books.... here is an example
Bad stuff:
//////////// set / get bL2R
if (![[NSUserDefaults standardUserDefaults]
boolForKey:kL2RomanizationChoice]) {
[[NSUserDefaults standardUserDefaults]
setBool:YES
forKey:kL2RomanizationChoice];
bL2R = YES;
NSLog(#"L2Rom not found, set to YES.");
}
else {
bL2R = [[NSUserDefaults standardUserDefaults]
boolForKey:kL2RomanizationChoice];
NSLog(#"L2Rom found.");
if (bL2R) {
NSLog(#"L2Rom found to be YES.");
}
}
Good stuff:
if (![defaults boolForKey:kL2RomanizationChoice])
[defaults setBool:YES forKey:kL1RomanizationChoice];
L2String_Setting = [defaults objectForKey:kSecondLangChoice];
bL2R = [defaults boolForKey:kL2RomanizationChoice];
Update: sadly this only seemed to work briefly, and now is failing again... using Xcode 4.5.2. may just swap out bools for integers...
XCode 4.6 seems to have the same problem highlighted by hangzhouharry. A useful call is [[NSUserDefaults standardUserDefaults] dictionaryRepresentation] to see if your key values are looking the way they should.
For example -> autoLogout = 0;
which was set as a Bool, [settings boolForKey:#"autoLogout"] returns nothing
[settings integerForKey:#"autoLogout"] returns 0 (as, sort of, expected)