UITableView - 核心数据应用程序中的表视图崩溃,因为删除后行数无效

时间:2013-06-30 04:30:56

标签: ios core-data uitableview

我正在创建一个核心数据示例,其中我想删除托管对象(此处称为项目)。删除管理对象似乎有效,但刷新tableView是一个问题。以下是我在调用tableView: numberOfRowsInSection:时应用崩溃时收到的日志消息。

  

由于未捕获的异常而终止应用   'NSInternalInconsistencyException',原因:'无效更新:无效   第0节中的行数。包含在中的行数   更新后的现有部分(13)必须等于数量   更新前的该部分中包含的行(13),加号或减号   从该部分插入或删除的行数(插入0,   删除1)加上或减去移入或移出的行数   该部分(0移入,0移出)。'

这里删除前的行数是14,后面是13。请参阅我用于A的方法。获取行数,这应该等于核心数据中“项目”的数量。 B.删除项目。 C.设置tableView中的行数。

一个。

-(void) setupFetchResultsController {
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Project"];
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    NSError *error;
    fetchedProjects = [managedObjectContext executeFetchRequest:request error:&error];
    if (fetchedProjects == nil) {
        // Handle the error.
    }
    self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:nil];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 
    selectedProject = [self.fetchedResultsController objectAtIndexPath:indexPath];
    [managedObjectContext deleteObject:selectedProject];
        //setting up the fetch results controlleris intended to get the number rows correctly by fetching the existant projects. In the above log, the result would be 14 (not 13) without this line.  Crashes with or without this line. 
    [self setupFetchResultsController];    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

下进行。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {   
    int noOfRows = [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
    return noOfRows;    
}

2 个答案:

答案 0 :(得分:2)

这与核心数据无关。

您必须确保表中的行数,并且数据源中的行数始终相同。

如果您需要删除一行,则需要从数据源中删除该行,将其从表中删除,但是 - > - >你需要在这两行代码之间做到这一点:

[_tableView beginUpdates];

// here delete from data source, and from the table.

[_tableView endUpdates];

答案 1 :(得分:1)

我认为问题是我不需要使用以下方式手动删除行:

if (editingStyle == UITableViewCellEditingStyleDelete) {
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }

我认为FetchResultsController可以解决这个问题。无论如何,我删除了线,它的工作原理。