Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving and displaying data with NSUserDefaults

I've saved some input from a UITextField using the following code:

 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:myTextField.text forKey:@"myTextFieldKey"];
    [defaults synchronize];

I'd like to display this saved text on a UILabel in another view controller.

I tried this:

  myLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"myTextFieldKey"];

but nothing displays. Any help with this would be great. thanks.

like image 596
hanumanDev Avatar asked Jan 18 '26 20:01

hanumanDev


2 Answers

Well the loading and saving code is correct, so it looks like the problem is something else.

Try this to debug:

NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"myTextFieldKey"];
NSLog(@"Value from standardUserDefaults: %@", aValue);

NSLog(@"Label: %@", myLabel);
myLabel.text = aValue;

Now you will see if the value retriever from the NSUserDefaults is set and if the label is assinged.

like image 136
rckoenes Avatar answered Jan 20 '26 09:01

rckoenes


 [[NSUserDefaults standardUserDefaults] setValue:myTextField.text forKey:@"myTextFieldKey"];
 [[NSUserDefaults standardUserDefaults] synchronize];

After that use valueForKey not objectForKey:

myLabel.text = [[NSUserDefaults standardUserDefaults] valueForKey:@"myTextFieldKey"];
like image 44
LightNight Avatar answered Jan 20 '26 09:01

LightNight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!