我在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
这里出了什么问题?
答案 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。由于您的用户默认值仅保存在秒中。
这样它只显示第二个。
答案 4 :(得分:0)
您的代码是覆盖最后一个值,从NSUserDefault中删除以前的值。您必须使用数组来存储所有值,并且已将数组保存到NSUserDefault中。
NSMutableArray *aryDataDefault = [[NSUserDefaults standardUserDefaults] valueForKey:@"YourKey"];
[aryDataDefault addObject:textfield.text];
[[NSUserDefaults standardUserDefaults] setObject:aryDataDefault forKey:@"YourKey"];
[[NSUserDefaults standardUserDefaults] synchronize];