Question

I have the next problem. This are my view controllers:

my viewcont

So I want that when something is written Into the texfield appears in the tableview, but the reload data is not working! Heres my code:

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if (!self.tasks) self.tasks = [NSMutableArray new];
    [self.tasks addObject:textField.text];
    [userDefaults setObject:self.tasks forKey:@"tasks"];
    NSLog(@"tasks:%@", [[NSUserDefaults standardUserDefaults]objectForKey:@"tasks"]);
    NSLog(@"number of tasks:%d", self.tasks.count);
    TasksTableViewController *tasksTable = [[TasksTableViewController alloc]init];
    [tasksTable.tableView reloadData];
    [textField resignFirstResponder];
    return YES;
}

And in the tasktableviewcontroller:

[super viewDidLoad];
    if (!self.TasksArray) self.TasksArray = [NSMutableArray new];
    self.TasksArray = [[NSUserDefaults standardUserDefaults]objectForKey:@"tasks"];

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    NSLog(@"number of tasks when tableview:%d", self.TasksArray.count);
        //return self.TasksArray.count;
    return self.TasksArray.count;
}

Im only calling the count of cells for testing, and always shows 1 cell.

So whats wrong?? In the NSLogs all is right, prints the strings of the textfield and the number of Objects at the array, So hope you Help me, thanks!

Was it helpful?

Solution

TasksTableViewController *tasksTable = [[TasksTableViewController alloc]init];

This line creates an entirely new table view controller. You need to find the one that is currently on display and pass it the data instead. (presumably the table view controller gets tasks from user defaults when it reloads).

How you do that depends on the container you have. You could:

  1. Navigate through the container, nav controller, top view controller
  2. Use KVO in the table controller to observe user defaults
  3. Post a notification when you save new tasks and observe it in the table controller
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top