ios核心数据:确保从数据源中删除对象

时间:2017-11-16 22:47:16

标签: ios objective-c uitableview core-data nsfetchrequest

更新:在评论中,有人指出我不必要地调度到主线程。删除调度和不必要的begin/end updates之后,现在当我尝试删除一个单元格时,它会调用didChangeObject,其中包含NSFetchedResultsChangeUpdate(而非NSFetchedResultsChangeDelete),调用{configureCell 1}}。

在以下方法中,崩溃程序的行为CollectedLeaf* theCollectedLeaf = [collectionFetchedResultsController objectAtIndexPath:indexPath];。崩溃日志为no section at index 20 in sections list

- (void)configureCell:(SpeciesCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    CollectedLeaf* theCollectedLeaf = [collectionFetchedResultsController objectAtIndexPath:indexPath];
    [cell setCollectedLeaf:theCollectedLeaf];
}

每次滑动删除表格中的单元格时,我都会收到Invalid update: invalid number of rows in section错误。我专门在[_table endUpdates]的{​​{1}}处获得了断点。

在许多SO帖子中,出现此错误的原因是在从表中删除行之前未从数据源中删除该对象。我从controllerDidChangeContent中的数据源中删除了该对象,该对象在commitEditingStyle deleteRowsAtIndexPaths之前调用。

即使我的订单,我仍然得到didChangeObject的事实让我认为我没有正确/成功地从数据源中删除它。我还是iOS新手 - 如何确保从核心数据中删除对象?

Invalid update

1 个答案:

答案 0 :(得分:0)

This post saved me

objectAtIndexPath非常错误,只能在边界检查中调用,所以我现在使用nest if中的核心数据对象完成所有工作

    CollectedLeaf* theCollectedLeaf = nil;
    if ([[collectionFetchedResultsController sections] count] > [indexPath section]){
        id <NSFetchedResultsSectionInfo> sectionInfo = [[collectionFetchedResultsController sections] objectAtIndex:[indexPath section]];
        if ([sectionInfo numberOfObjects] > [indexPath row]){
            theCollectedLeaf = [collectionFetchedResultsController objectAtIndexPath:indexPath];

        //do whatever else I need, delete the object, etc
        }

    }

正如链接帖子描述的那样,

  

&#34;您获得例外的原因是该状态   NSFetchedResultsController与状态不同步   tableview。当你的崩溃发生时,tableView只是问你的   委托方法(numberOfSectionsInTableView和   tableView:numberOfRowsInSection:用于行数和节数。   当它询问时,NSFetchedResultsController中有数据,并且   给出正值(1节,3行)。但介于两者之间   发生和你的崩溃,由实体代表的实体   NSFetchedResultsController已从中删除   的NSManagedObjectContext。现在正在调用cellForRowAtIndexPath:   使用过时的indexPath参数。&#34;