【发布时间】:2016-04-25 23:08:31
【问题描述】:
我有一个连接到核心数据的 UITableView。表格视图具有动态单元格并将行分组为部分(类别)。
我可以通过在部分之间拖动来移动行,这适用于核心数据,除非我拖动一行并且部分变为空。我希望节标题消失,但它保留为标题,内部没有行。然后,如果我尝试向后拖动一行,则会出现错误。
我已经为 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 中。 非常感谢任何解决此问题的帮助。
【问题讨论】:
标签: swift uitableview core-data