I’ve got a sublass of UITableViewController which I use to add a new data for a new cell within another Table. That means, I’ve got a “Cancel” and a “Save” button at the top to save the data and get back to the table where to add the new object into. I show the adding controller modally.
My problem is though that I don’t know how to get the data from the user input cells of the tableView in my UITableViewController subclass to save them in my CoreData file.
Here’s the code how I try it – but at the console I just get (nil) for the persons name:
- (void)save
{
NSLog(@"Saving ...");
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
UITableViewCell *cell = [self tableView:[self tableView] cellForRowAtIndexPath:indexPath];
NSString *personName = [[cell textField] text];
NSLog(@"New Person: %@", personName);
// Do saving with Core Data and updating here.
[self dismissModalViewControllerAnimated:YES];
}
I guess you will also need the following method to understand the problem:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
EditableDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[EditableDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.accessoryType = UITableViewCellAccessoryNone;
if (indexPath.section == 0) {
[cell.textField setPlaceholder:@"Name"];
} else {
switch (indexPath.row) {
case 0:
[cell.textField setPlaceholder:@"Birth Year"];
break;
case 1:
[cell.textField setPlaceholder:@"Weight in kg"];
break;
case 2:
[cell.textField setPlaceholder:@"Height in cm"];
break;
case 3:
[cell.textField setPlaceholder:@"Sex"];
break;
default:
break;
}
}
return cell;
}
I really can’t find the failure. In my understanding it should work this way … but it doesn’t. Could anyone please help?
Don’t call your table view datasource method to get the value in the cell. Get it directly from the table view instead.
Instead of this:
Do this:
Doing it the way you are doing is essentially recreating the cell and so losing the value you have entered. The datasource method is only meant to be called by the table to work out what to display.