NSFetchedResultsController添加实体在tableView中插入空行

时间:2012-10-13 10:08:57

标签: iphone objective-c ios uitableview nsfetchedresultscontroller

在我的应用程序中,我有一个viewcontroller,它是NSFetchedResultsController的委托和UITableView的委托和数据源。

当按下导航控制器中的添加按钮时,正确推送下一个视图,我可以正确添加新的Person实体。

我的问题是,当按下添加按钮时,在推送新视图时会向tableView添加一个空行,并且在正确创建新实体记录后仍然存在该行

这是添加按钮的目标操作:

- (void)addPerson:(id)sender
{
    AddPersonViewController *addPersonController = [[AddPersonViewController alloc] initWithNibName:@"AddPersonViewController" bundle:nil];

    [addPersonController setPerson:[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext]];

    [self.navigationController pushViewController:addPersonController animated:YES];
}

创建空白行的代码(来自NSFetchedResultsControllerDelegate的apple文档)位于:

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath {

    UITableView *tableView = self.tableView;

    switch(type) {

        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeUpdate:
            [self configureCell:[tableView cellForRowAtIndexPath:indexPath]
                    atIndexPath:indexPath];
            break;

        case NSFetchedResultsChangeMove:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}

有关如何停止创建此空白行的任何想法?

1 个答案:

答案 0 :(得分:1)

致电

[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext]
addPerson中的

创建一个新的 Person 对象,并将其添加到托管对象上下文中。如果表视图的获取结果控制器配置为获取所有 Person 对象,则会为此新对象生成一个新的(空白)表行。

我不知道你的AddPersonViewController是如何运作的。如果它修改了通过setPerson给出的对象,则应更新表格行。如果它创建了一个新的 Person 对象,那么第一个(空白)条目将保留。

您可能应该延迟创建新的 Person 对象,直到AddPersonViewController具有实际创建和填充对象的所有数据。您可以将insertNewObjectForEntityForName:调用移动到AddPersonViewController,或者使用从AddPersonViewController调用的表视图控制器中的委托方法来执行此操作。