我正在使用 NSFetchedResultsController。我找不到任何简单的教程来遍历它Swift 3。
所以这是我到目前为止所做的。我已经使用NSFetchedResultsController从核心数据中获取插入数据的成功填充了我的表。我在我的核心数据模型中创建了一个名为的属性,该属性orderPosition声明为Int32. 关于在插入时将数据添加和保存到核心数据,我没有对这个属性做任何事情。
在我func初始化 的fetch中NSFetchedResultsController,我修改了我的排序描述符以包含以下代码:
let sortDescriptor = NSSortDescriptor(key: "orderPosition", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
Run Code Online (Sandbox Code Playgroud)
然后我实现了tableViewfunc:
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
attemptFetch()
var objects = self.controller.fetchedObjects!
self.controller.delegate = nil
let object = objects[sourceIndexPath.row]
objects.remove(at: sourceIndexPath.row)
objects.insert(object, at: destinationIndexPath.row)
var i = 0
for object in objects {
object.setValue(i += 1, forKey: "orderPosition")
}
appdel.saveContext()
self.controller.delegate = self
} …Run Code Online (Sandbox Code Playgroud)