如何使用NSUserDefaults保存和加载UITextField?

时间:2011-09-06 10:06:44

标签: ios xcode uitextfield nsuserdefaults viewdidload

  

可能重复:
  How would I save and load a UITextField?

我已经尝试过一切,不幸的是没有什么对我有用。我可能已经测试了大约10种保存和加载UITextFields的方法,但它们不起作用。我有六个UITextFields,想要在按下按钮时保存它们,并在调用viewDidLoad时加载。

我可以得到一些帮助,因为我必须在接下来的一两天内发布应用程序,但我仍然无法做到这一点......

谢谢,

詹姆斯

3 个答案:

答案 0 :(得分:9)

NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];

NSString* textField1Text = textField1.text;
[defaults setObject:textField1Text forKey:@"textField1Text"];

NSString* textField2Text = textField2.text;
[defaults setObject:textField2Text forKey:@"textField2Text"];

NSString* textField3Text = textField3.text;
[defaults setObject:textField3Text forKey:@"textField3Text"];

NSString* textField4Text = textField4.text;
[defaults setObject:textField4Text forKey:@"textField4Text"];

NSString* textField5Text = textField5.text;
[defaults setObject:textField5Text forKey:@"textField5Text"];

NSString* textField6Text = textField6.text;
[defaults setObject:textField6Text forKey:@"textField6Text"];

[defaults synchronize];

NSString* temp = [defaults objectForKey:@"textField1Text"];
NSString* temp = [defaults objectForKey:@"textField2Text"];
NSString* temp = [defaults objectForKey:@"textField3Text"];
NSString* temp = [defaults objectForKey:@"textField4Text"];
NSString* temp = [defaults objectForKey:@"textField5Text"];
NSString* temp = [defaults objectForKey:@"textField6Text"];

NSLog(@"%@,%@,%@,%@,%@,%@",temp1,temp2,temp3,temp4,temp5,temp6);

新编辑

  - (IBAction) saveBtnPresssed : (id) sender
  {

        NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];

        NSString* textField1Text = textField1.text;

        [defaults setObject:textField1Text forKey:@"textField1Text"];

        NSString* temp = [defaults objectForKey:@"textField1Text"];

        NSLog(@"%@",temp);

  }

答案 1 :(得分:2)

link可能对您有所帮助。

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

//保存NSString

[prefs setObject:@"your textField text" forKey:@"keyToLookupString"];

答案 2 :(得分:2)

设置对象后,需要调用synchronize将其保存并提交到用户默认值中(使用上面评论中提供的示例):

- (IBAction)doSaveAllNotes{

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs setObject:Assignment1.text forKey:@"Assignment1Text"];
    [prefs synchronize]; // This is to save it and is pretty important!

    NSLog(@"Saved All Notes");
}