NSUserDefaults仅保存最后输入的数据

时间:2014-03-06 08:07:56

标签: ios iphone nsuserdefaults

我在ViewController2中点击按钮时使用NSUserDefaults保存Textfield文本  我的代码是

ButtonClick()
{
    NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
    [userDefaults setObject:keyWordField.text forKey:@"Keywords"];
    [userDefaults synchronize];
}

Then ViewDidLoad method i am Retrieving like this
-(void)viewDidLoad
{

NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
[keyWordArray addObject:[userDefaults objectForKey:@"Keywords"]];
[userDefaults synchronize];

}

这里我将这个keyWordArray分配给tableview 比如cell.textlabel.text =[keyWordArray objectAtIndex:indexPath.row];

First i entered text(First) in textfield and click button it is showing in table like
     First
Second time i entered text (second) in textfield and click button it is showing table like
      First
      Second
Here everything working fine. The problem is when i come to viewController2 from ViewController1. It is showing last entered value only 
like
      Second

这里出了什么问题?

5 个答案:

答案 0 :(得分:1)

试试这个

- (IBAction)buttonclick:(id)sender {

[keyWordArray addObject:keyWordField.text];
NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
[userDefaults setObject:keyWordArray forKey:@"Keywords"];
[userDefaults synchronize];
[selt.tableView reload];  //reload the table every time a new text is added
}

-(void)viewDidLoad {
 if([[NSUserDefaults standardUserDefaults] objectForKey:@"Keywords"]==nil){
  keyWordArray = [[NSMutableArray alloc] init];
 }
 else{
 keyWordArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"Keywords"];
 }
}

答案 1 :(得分:0)

试试这个,

- (IBAction)buttonclick:(id)sender {

    [keyWordArray addObject:keyWordField.text];
    NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
    [userDefaults setObject:keyWordArray forKey:@"Keywords"];
    [userDefaults synchronize];
}

-(void)viewDidLoad
{

    NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"Keywords"];

    if (!array) {
        keyWordArray = [[NSMutableArray alloc] init];
    } else {
        keyWordArray = [NSMutableArray arrayWithArray:nameArray];

    }
}

答案 2 :(得分:0)

因为你要覆盖你的

[userDefaults setObject:keyWordField.text forKey:@"Keywords"];
每隔一段时间,数组中的每个对象都会引用你的[userDefaults setObject:keyWordField.text forKey:@"Keywords"];对象,问题来了

答案 3 :(得分:0)

因为如果你导航到另一个viewController。由于您的用户默认值仅保存在中。

  1. 通过viewDidLoad加载后弹出。到目前为止它的第二个字符串只保存在User Default。
  2. 这样它只显示第二个。

答案 4 :(得分:0)

您的代码是覆盖最后一个值,从NSUserDefault中删除以前的值。您必须使用数组来存储所有值,并且已将数组保存到NSUserDefault中。

NSMutableArray *aryDataDefault = [[NSUserDefaults standardUserDefaults] valueForKey:@"YourKey"];
[aryDataDefault addObject:textfield.text];
[[NSUserDefaults standardUserDefaults] setObject:aryDataDefault forKey:@"YourKey"];
[[NSUserDefaults standardUserDefaults] synchronize];