Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot set NSUserDefaults field

I have the following code in my initialization (first time) of my app:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *uid=@"1";
[defaults setObject:uid forKey:@"init_val"];
[defaults synchronize];

Much later in the code (in response to a button press) I check the value using:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *initVal=[defaults objectForKey:@"init_val"];

initVal is always nil. I have checked and init_val is set up exactly the same in my settings bundle as another field that I can set and read from without issue (they are both set up with a single field named "Key".

like image 692
mlewis54 Avatar asked Jan 31 '11 20:01

mlewis54


2 Answers

@mlewis54:

You can try this code. I am very sure that it will work for you.

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *uid=@"1";
[defaults setObject:uid forKey:@"init_val"];
[defaults synchronize];

For Retrieving Data You Should Use The Following Code :

NSString *initVal=[[NSUserDefaults standardUserDefaults] valueForKey:@"init_val"];

OR

NSString *initVal=[[NSUserDefaults standardUserDefaults] objectForKey:@"init_val"];

EDIT:

If still it gives nil, then you can use the following code:

NSString *initVal=[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"init_val"]];

OR

NSString *initVal=[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"init_val"]];

Hope this helps you.

like image 98
Parth Bhatt Avatar answered Sep 30 '22 04:09

Parth Bhatt


Decelare this at an event on click of button ...

NSUserDefaults *savedData = [NSUserDefaults standardUserDefaults];
[savedData setObject:userEmailTextField.text forKey:@"userid"];

and on load load the data and check the value you have entered is showing or not...

userEmailTextField.text =[[NSUserDefaults standardUserDefaults]objectForKey:@"userid"];
like image 23
breakfreehg Avatar answered Sep 30 '22 04:09

breakfreehg