gpt4 book ai didi

ios - NSUserDefaults 只保存最后输入的数据

转载 作者:行者123 更新时间:2023-11-29 12:51:57 25 4
gpt4 key购买 nike

我在 ViewController2 中单击按钮时使用 NSUserDefaults 保存文本字段文本 我的代码是

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

这里出了什么问题?

最佳答案

试试这个

- (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"];
}
}

关于ios - NSUserDefaults 只保存最后输入的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22218577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com