iphone - Xcode:使用 NSUserDefaults 和 TableView 保存数据问题

标签 iphone xcode uitableview ios5 nsuserdefaults

我试图通过 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/

相关文章:

iphone - 进行 Facebook 集成时出错

jquery - 在没有 mac 的情况下创建 iPhone webapp

iphone - 小地方的增强现实 iOS 应用程序 - 可能吗?

xcode - 将构建上传到 iTunes Connect 问题

ios - swift 将表格 View 的大小调整到最后一行

iphone - 通过 WiFi 连接的设备与 Web 服务器建立长时间开放连接会出现哪些问题?

ios - 如何升级到 Xcode 4.5

ios - 当我从 URL 获取文本时,如何删除那些行?

ios - handleKeyboardWillShow 通知处理

iphone - iOS自定义UITableView中的滚动条