所以我有一个tableView和一个详细视图。我在tableView中有一个额外的行来“添加”一条记录。当我点击新按钮时,我将一个零对象发送到我的详细视图,这与我用于编辑现有行的对象相同。我使用以下代码:
- (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];
}
当我保存核心数据时,我在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];
}
}
然后我用reloadData更新我的tableView,但它只更新修改后的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];
}
这会将新行保存到我的数据库,但新行永远不会出现。 InsertRows实际上是coreDumps在我身上。我很确定我需要使用insertRowsAtIndexPaths但我不知道在哪里放置它所以它会在我将对象添加到CoreData后执行。有任何想法吗?
答案 0 :(得分:0)
您忘记将新创建的汽车插入listOfCars数组。