代码之家  ›  专栏  ›  技术社区  ›  unsorted

从删除不在核心数据中的虚拟行时出现核心数据异常

  •  0
  • unsorted  · 技术社区  · 14 年前

    我有一个 UITableView 与核心数据相关。当没有条目时,我修改表以确保节=1,行=1,并且此行显示的文本表示“您的表是空的;使用+按钮添加一个新项”。

    但是,当用户通过单击+按钮添加第一个项目时,核心数据抛出一个异常,即更新后的行数(1)不等于更新前的行数(1)加或减(插入1,删除0)。这是有意义的,因为核心数据可能查询与我的TableView相同的函数( numberOfSectionsInTableView numberOfRowsInSection:section )但是,如何告诉核心数据我对TableView撒谎,更新之前的行数实际上是0?

    3 回复  |  直到 13 年前
        1
  •  0
  •   unsorted    14 年前

    好吧,我想我想用一种非常下流的方法来解决这个问题,如果我真的保持单身 UITableView . 写下来以备将来有帮助。

    基本上,创建一个 BOOL isUpdating 记录当前是否正在更新表。实施 numberOfRowsInSection:section 应检查是否 self.isUpdating 为真;如果为真,则返回“谎言”行数(即 NSFetchedResultsController 需要表具有),否则返回要告知TableView的行数。然后在中将I更新设置为“真” controllerWillChangeContent 回到错误的 controllerDidChangeContent .

        2
  •  0
  •   Marcus S. Zarra    14 年前

    它将有助于显示如何添加行、维护状态等的代码。否则,任何答案都只是非常一般或猜测。

        3
  •  0
  •   Matthias    13 年前

    您可以在 NSFetchedResultsControllerDelegate 类似于此示例中的方法

    - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
               atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
      switch(type) {
        case NSFetchedResultsChangeInsert:
          if ([[self.fetchedResultsController sections] count] != 1) {
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
          } else {
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
          }
          break;
        case NSFetchedResultsChangeDelete:
          if ([[self.fetchedResultsController sections] count] != 0) {
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
          } else {
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
          }
          break;
      }
    }
    

    如果您的表中没有节,请在 controller:didChangeObject:atIndexPath:forChangeType:newIndexPath: 方法代替。