简体   繁体   English

NSUserDefaults在UITableViewController中添加行

[英]NSUserDefaults to add row in a UITableViewController

I am trying to use NSUserDefaults to store a UITextField text and to retrieve it in another controller after you press Done button while editing. 我尝试使用NSUserDefaults来存储UITextField文本,并在编辑时按“完成”按钮将其检索到另一个控制器中。

in the controller where the user put information i code this : 在用户放置信息的控制器中,我对此进行编码:

-(IBAction)confirmAction:(id)sender{

UIViewController *prevVC = [self.navigationController.viewControllers objectAtIndex:1];
[self.navigationController popToViewController:prevVC animated:YES];

NSUserDefaults *try = [NSUserDefaults standardUserDefaults];
[try setObject:self.nameTextField.text forKey:@"name"];
[try synchronize];

}

and in the other controller i use this : 在另一个控制器中,我使用这个:

-(void)doneAction:(id)sender{

[self.tableView setEditing:NO animated:NO];

self.navigationItem.leftBarButtonItem = nil;

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editButtonClicked:)];

NSUserDefaults *try = [NSUserDefaults standardUserDefaults];
[ingredients addObject:[try stringForKey:@"name"]];



}

why i can't see any results. 为什么我看不到任何结果。 nothing is added in the tableview. 表格视图中未添加任何内容。 why? 为什么? did i write something wrong? 我写错了吗?

The most likely reason why you do not see the changes is that the UITableView does not know that you have added a new item to the ingredients array. 您看不到更改的最可能的原因是UITableView不知道您已向ingredients数组添加了新项目。 In MVC terms, your controller made changes to the model, but it did not notify the view of that change. 用MVC术语来说,您的控制器对模型进行了更改,但没有将更改通知给视图。

You need to call [self.tableView reloadData]; 您需要调用[self.tableView reloadData]; at the end of your doneAction: method: doneAction:方法的末尾:

-(void)doneAction:(id)sender {
    [self.tableView setEditing:NO animated:NO];
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editButtonClicked:)];
    NSUserDefaults *try = [NSUserDefaults standardUserDefaults];
    [ingredients addObject:[try stringForKey:@"name"]];
    [self.tableView reloadData];
}

You should add [self.tableView reloadData]; 您应该添加[self.tableView reloadData]; after [ingredients addObject:[try stringForKey:@"name"]]; [ingredients addObject:[try stringForKey:@"name"]];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM