开发者

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 di开发者_JAVA百科splay 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.


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.


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

After that use valueForKey not objectForKey:

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


Try:

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


Check that myTextField and myLabel aren't nil.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜