我试图通过 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;
}
最佳答案
您的代码中有两个问题:
您没有刷新表格 View 。您可以通过调用来做到这一点:
[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];
附注当然,您需要在 viewDidLoad
中相应地设置您的 dataArray
:
self.dataArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"myTxtList"];
关于iphone - Xcode:使用 NSUserDefaults 和 TableView 保存数据问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10499736/