[英]Xcode: saving data issue with NSUserDefaults and TableView
我正在尝试通过NSUserDefaults保存数据并在tableView上查看它,但是单击“保存”按钮后什么也没有发生,在我停止并再次运行该应用程序之后,我保存的数据每次在覆盖时都可以看到旧数据。 难道我做错了什么? 还是我应该使用与NSUserDefaults不同的东西?
提前致谢。
-(IBAction)save{
NSUserDefaults *add1 = [NSUserDefaults standardUserDefaults];
[add1 setObject:txt1.text forKey:@"txt1"];
[add1 synchronize];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
self.dataArray = [NSArray arrayWithObjects:[prefs objectForKey:@"txt1"], nil];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *string = [dataArray objectAtIndex:indexPath.row];
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text=string;
return cell;
}
正如A for Alpha所说,尝试&另外我也对您的save
方法定义有疑问。 只需尝试将其更改为以下内容
-(IBAction)save:(id)sender{
NSUserDefaults *add1 = [NSUserDefaults standardUserDefaults];
[add1 setObject:txt1.text forKey:@"txt1"];
[add1 synchronize];
[tableView reloadData];
}
这可能对你有用。
您的代码中有两个问题:
您没有刷新表格视图。 您可以通过致电:
[self.tableView reloadData]; // Or whatever property is pointing to your tableview
每次保存值时,都将其保存在相同的键( txt1
)下,这就是每次都覆盖的原因。 如果您想要一个项目列表(一个数组)并将该项目追加到该数组中,则可以执行以下操作:
NSMutableArray *myList = [[[NSUserDefaults standardUserDefaults] valueForKey:@"myTxtList"] mutableCopy];
[myList addObject:txt1.text];
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithArray:myList] forKey:@"myTxtList"];
[add1 synchronize];
self.dataArray = myList;
[self.tableView reloadData];
PS当然,您需要在viewDidLoad
相应地设置dataArray
:
self.dataArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"myTxtList"];
我想您将数据保存在userDefaults
之后需要调用[yourTableView reloadData]
。 这应该可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.