UITableViewCells 的保存顺序

par*_*aro 4 core-data uitableview nsfetchedresultscontroller swift ios8

我在 tableview 中添加了对单元格进行排序/重新排序的选项。我使用了本教程:http : //www.ioscreator.com/tutorials/reordering-rows-table-view-ios8-swift。现在我想问一下如何保存单元格的排序/顺序?我还使用 Core Data 和fetchedResultsController.

Log*_*ier 5

向用于存储排序顺序的 Core Data 模型对象添加一个额外的属性。例如,您可以有一个orderIndex属性:

class MyItem: NSManagedObject {

    @NSManaged var myOtherAttribute: String
    @NSManaged var orderIndex: Int32

}
Run Code Online (Sandbox Code Playgroud)

然后,在您的排序描述符中将此属性用于您的 fetched results 控制器的 fetch 请求:

fetchRequest.sortDescriptors = [NSSortDescriptor(key: "orderIndex", ascending: true)]
Run Code Online (Sandbox Code Playgroud)

最后,更新orderIndexUITableViewDataSource 方法中的属性:

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

    if var items = fetchedResultsController.fetchedObjects as? [MyItem],
        let itemToMove = fetchedResultsController.objectAtIndexPath(sourceIndexPath) as? MyItem {

            items.removeAtIndex(sourceIndexPath.row)
            items.insert(itemToMove, atIndex: destinationIndexPath.row)

            for (index, item) in enumerate(items) {
                item.orderIndex = Int32(index)
            }
    }
}
Run Code Online (Sandbox Code Playgroud)