So I have a tableView and a detail view. I have an extra row in my tableView to “Add” a record. When I click on the new button I send a nil object to my detail view which is the same that I use for editing an existing row. I use the following code for that:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
new = NO;
NSUInteger row = [indexPath row];
SavedCarDetailController *detailController = [[SavedCarDetailController alloc] initWithNibName:@"SavedCarDetailController" bundle:nil];
if(indexPath.row >= [listOfCars count]){
NSLog(@"New Car");
detailController.car = nil;
new = YES;
} else {
new = NO;
detailController.car = [listOfCars objectAtIndex:row];
}
detailController.managedObjectContext = self.managedObjectContext;
[self.navigationController pushViewController:detailController animated:YES];
[detailController release];
}
When I save my core data stuff I execute this in my detailController
- (void)viewWillDisappear:(BOOL)animated {
NSError * e = nil;
if(self.New){
NSLog(@"New Car Saving");
NSManagedObject * obj = [NSEntityDescription insertNewObjectForEntityForName:@"Cars" inManagedObjectContext: managedObjectContext];
[obj setValue:Name.text forKey:@"name"];
[obj setValue:Year.text forKey:@"Year"];
[obj setValue:Notes.text forKey:@"Notes"];
} else {
NSLog(@"Updating exiting car");
car.Name = Name.text;
car.Year = Year.text;
car.Notes = Notes.text;
}
[managedObjectContext save:&e];
if(e){
NSLog(@"Error occurred, %@", e);
}
if(self.New){
} else {
// [self.parentViewController.tableView reloadData];
}
}
Then I update my tableView with reloadData but it only updates the modified feild
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if(new){
NSInteger row = [listOfCars count];
NSLog(@" row %i", row);
NSArray *paths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:row inSection:0]];
//NSArray * foo = [NSArray arrayWithArray:<#(NSArray *)array#>
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
new = NO;
}
//This only works with "changed data" not new rows.
[self.tableView reloadData];
}
This saves new rows to my database but the new row never appears. The InsertRows actually coreDumps on me. I am pretty sure I need to use the insertRowsAtIndexPaths but I have no clue where to put it so it will be executed once I have added the object to CoreData. Any ideas?
You forget to insert the newly created car to the listOfCars array.