如何从节中移动最后一行时删除节标题

时间:2016-04-25 23:08:32

标签: swift uitableview core-data

我有一个连接到核心数据的UITableView。 tableview具有动态单元格,并将行分组为多个部分(类别)。

我可以通过在各个部分之间拖动来移动行,这可以很好地处理核心数据,除非我拖动一行并且该部分变空。我希望节标题消失,但它保持为标题,内部没有行。然后,如果我尝试拖回一行,我会收到错误。

我已经为didChangeObject和didChangeSection实现了NSFetchedResultsController函数。但是当拖动行时我发现我必须将fetchedResultsController的委托设置为nil。

以下是处理移动的代码部分。

func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {

  // Create array of fetched  items from the stack
  var items = fetchedResultsController.fetchedObjects! as! [Item]

  // Convert the index paths to row number in the table.
  let destinationRow = rowAtIndexPath(destinationIndexPath)
  var sourceRow = rowAtIndexPath(sourceIndexPath)

  // Source row has to be reduced by one if it was moved to lower section because tableview is counting the row twice, once in the new section and once as the row index in the old section.
  if sourceIndexPath.section > destinationIndexPath.section {
    sourceRow -= 1
  }

  let newCategory = fetchedResultsController.sections![destinationIndexPath.section].name

  // Get the  item of from the source index path and update the category
  let item = fetchedResultsController.objectAtIndexPath(sourceIndexPath) as! Item
  item.category = newCategory

  // Do not trigger delegate methods when changes are made to core data
  fetchedResultsController.delegate = nil

  // Move the  item in core data
  items.removeAtIndex(sourceRow)
  items.insert(item, atIndex: destinationRow)


  do {
    try coreDataStack.context.save()
  } catch {
    fatalCoreDataError(error)
  }

  fetchedResultsController.delegate = self
}

我没有找到任何回答这个的问题,特别是在Swift中没有。 任何帮助解决这个问题都非常感谢。

1 个答案:

答案 0 :(得分:0)

为什么需要将delegate设置为nil?如果这是因为一个错误表明您已经错误地实现了某些内容。

回答您的原始问题:由于您使用的是NSFetchedResultsController,因此NSFetchedResultsControllerDelegate方法会自动删除该部分controller(_, didChangeSection, atIndex, forChangeType)

真正的问题是,为什么要将delegate设置为nil