NSUserDefaults is not saving any value in cocoa [duplicate] - objective-c

This question already has answers here:
Mac sandbox created but no NSUserDefaults plist
(5 answers)
Closed 5 years ago.
I am trying to save BOOL value and some simple string using NSUserDefaults. But NSUserdefaults is not saving any value. I have also used synchronize after saving the value into NSUserDefaults.The way I am using to save the BOOL into NSUserDefaults is as below.
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"loadfirsttimewindow"];
[[NSUserDefaults standardUserDefaults] synchronize];
And the way I am using to save the string into NSUserDefaults is as below.
[[NSUserDefaults standardUserDefaults] setValue:title1 forKey:#"item1"];
[[NSUserDefaults standardUserDefaults] synchronize];
So please let me know that where my NSUserDefaults value has been stored and why it is not saving any value into NSUserDefaults.
Simply I just want to save value which will remain saved even after the application has been closed.
The sample of code I have used for saving the value into NSUserDefaults in given below:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSLog(#"%hhd",[[NSUserDefaults standardUserDefaults] boolForKey:#"loadfirsttimewindow"]);
if (![[NSUserDefaults standardUserDefaults] boolForKey:#"loadfirsttimewindow"])
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"loadfirsttimewindow"];
[[NSUserDefaults standardUserDefaults] synchronize];
*I have written code for the thing I have to do only when the application is launched for the first time.*
}
else
{
*I have written code for the thing I have to after the application is launched for the first time.*
}
}

I have found my solution from the link given below:
Mac sandbox created but no NSUserDefaults plist
When you move the container while testing / debugging to the trash, the cfprefsd (see Activity Monitor) still keeps a link to the .plist. Empty the trash and force quit both cfprefsd (user and root).

Related

NSUserdefault not saving value ios9.3 , ios 10 , using side navigation

This issue has been cause of lots of frustration , as NSUserDefaults stopped working.
i am saving facebook information in userdefaults for later use , but it is returning nil.
Note : i get nil when i try to slide in side navigation (using SWRevealViewController) bar.
here is my code :
[[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:#"%#",[RespArray valueForKey:#"image_url"]] forKey:#"profilePic"];
[[NSUserDefaults standardUserDefaults] synchronize];
What i have tried :
- add/remove synchronize
- clearing all NSUserDefaults from app
- using setObject , SetValue for NSUserDefault key
- using NSString Stringwithformat , for retrieving strings.
i tried each and every solution available on SO and web.

Saving NSUserDefaults Issue?

i have been working on a app, and needed to store a string. I used this code to set the default:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:CertificateKey.stringValue forKey:#"SavedKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"%#",[defaults objectForKey:#"SavedKey"]);
I loged it, so i know it saved...well, it showed me the value.
When i open my application, I use this to retrieve the default:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[CertificateKey setStringValue:[defaults objectForKey:#"SavedKey"]];
[CertificateKey setTitleWithMnemonic:[defaults objectForKey:#"SavedKey"]];
[[NSUserDefaults standardUserDefaults] synchronize];
Why will it not get the default value? Did i not completely save it?
Don't quit the application by pressing the stop button in xcode. Instead, quit it by right clicking on the application icon and selecting "Quit".
Edit
Maybe the first time that you execute the application, you want to save some defaults but you don't want to set them the second+ time that the application runs.
For this purpose in some class initialize method register the defaults, like this:
+ (void) initialize
{
NSUserDefaults* defaults= [NSUserDefaults standardUserDefaults];
[defaults registerDefaults: #{} ];
// This case it's an empty dictionary, but you can put whatever you want inside it.
// just convert it to data if it's not an object storable to a plist file.
}
Also, you're using setValue:forKey: , that method is inherited from NSObject. Use setObject:forKey: .
And use finalize if you want to save the defaults at the end:
- (void) finalize
{
// Save the defaults here
}
You might have a problem because you are creating an instance of NSUserDefaults. From what I understand you are supposed to access it like so: [[NSUserDefaults standardUserDefaults] setValue:#"Pikachu" forKey:#"Best Pokemon Ever"]; [[NSUserDefaults standardDefaults] objectForKey:#"Best Pokemon Ever"]; Rather than actually creating an instance of it.

Trying to save and set UISwitch state with NSUserDefaults

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.

NSUserDefaults. setValue works, Not setBool

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)

How to fetch the value saved in NSUserdefault

I am trying to use NSUser Deafault in my application user have tp fillup 4 UITextFields. I am trying to save the fields so that on subsequent runs of the program that whatever they previously put will already be displayed in those UITextFields so the wont have to re-input it in - unless they want to edit something in which case they still have that option. I think that I have figured out a good way to save the strings using NSUserDefaults but now I am trying to figure out how to have those fields populate a UITextField - it doesnt seem as easy as if they were UILabels. This is the route I am attempting:
Now my value is being saved in nsuserDefalut,but hot how to fetch dat value next time(when i re start application (null appear on the uitext field)) ..I am trying this cods
NSUserDefaults *userData = [NSUserDefaults standardUserDefaults]; //Hooks.
NSString *placeHolderName = [userData stringForKey:#"name"];
urltextFieldNormal.text = placeHolderName;
Do you remember to sync NSUserDefaults when you save the strings?
[[NSUserDefaults standardUserDefaults] setObject:#"Hello mister nick" forKey:#"alarmsArray"];
[[NSUserDefaults standardUserDefaults] synchronize];
Cheers mate...