4

I added the option in my tableview to sort/reorder cells. I used this tutorial: http://www.ioscreator.com/tutorials/reordering-rows-table-view-ios8-swift. Now I'd like to ask how I can save the sorting/order of the cells? I also use Core Data and the fetchedResultsController.

paro
  • 217
  • 3
  • 10
  • 1
    While you implicitly included the steps you took in your link, you should write it out and not require visitors to go elsewhere to gather what you did. – neanderslob Aug 31 '15 at 23:03
  • Though it's in Objective C, [this tutorial](http://www.raywenderlich.com/999/core-data-tutorial-for-ios-how-to-use-nsfetchedresultscontroller) might help. – Craig Grummitt Sep 01 '15 at 00:07

1 Answers1

5

Add an extra attribute to your Core Data model object that is used to store the sort order. For example, you could have an orderIndex attribute:

class MyItem: NSManagedObject {

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

}

Then, use this attribute in your sort descriptor for your fetched results controller's fetch request:

fetchRequest.sortDescriptors = [NSSortDescriptor(key: "orderIndex", ascending: true)]

And finally, update the orderIndex property in your UITableViewDataSource method:

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)
            }
    }
}
Logan Gauthier
  • 393
  • 2
  • 6
  • Thanks a lot for your answer. I also like to order the rest of the cells which aren't reordered by date. Do you know how I could do this? – paro Sep 01 '15 at 19:45