hanumanDev
hanumanDev

Reputation: 6614

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.

Upvotes: 2

Views: 610

Answers (4)

LightNight
LightNight

Reputation: 1625

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

After that use valueForKey not objectForKey:

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

Upvotes: 3

Jim
Jim

Reputation: 73936

Check that myTextField and myLabel aren't nil.

Upvotes: 1

rckoenes
rckoenes

Reputation: 69469

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.

Upvotes: 4

ohho
ohho

Reputation: 51911

Try:

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

Upvotes: 1

Related Questions