Reorder rows and save update to core data

Viewed 603

I never imagined it'd be so hard to reorder a table and save the new order to Core Data (and perhaps I'm overthinking it). The bit of code below is throwing me the following error: "The number of rows contained in an existing section after the update must be equal to the number of rows contained in that section before the update."

override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    initializeFetchedResultsController()

    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context2: NSManagedObjectContext = appDel.managedObjectContext
    let request2 = NSFetchRequest(entityName: "Activities")
    let activityOrderSort = NSSortDescriptor(key: "activityOrder", ascending: true)
    request2.sortDescriptors = [activityOrderSort]

    let predicate = NSPredicate(format: "date == %@", date)
    request2.predicate = predicate

    var fetchResults2: [NSManagedObject]

    do {
        try fetchResults2 = (appDel.managedObjectContext.executeFetchRequest(request2) as! [NSManagedObject])

        if fromIndexPath.row > toIndexPath.row {
            for i in toIndexPath.row..<fromIndexPath.row {
                fetchResults2[i].setValue(i+1, forKey: "activityOrder")
            }
            fetchResults2[fromIndexPath.row].setValue(toIndexPath.row, forKey: "activityOrder")
        }
        if fromIndexPath.row < toIndexPath.row {
            for i in fromIndexPath.row + 1...toIndexPath.row {
                fetchResults2[i].setValue(i-1, forKey: "activityOrder")
            }
            fetchResults2[fromIndexPath.row].setValue(toIndexPath.row, forKey: "activityOrder")
        }

    } catch let error as NSError {
        print("Error: \(error.localizedDescription)")
    }

    do {
        try appDel.managedObjectContext.save()
    } catch let error as NSError {
        print("Saving error: \(error.localizedDescription)")
    }

    initializeFetchedResultsController()

}

Here is the initializeFetchedResultsController() code for reference:

func initializeFetchedResultsController() {

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    context = appDelegate.managedObjectContext

    let fetchRequest = NSFetchRequest(entityName: "Activities")
    let orderSort = NSSortDescriptor(key: "activityOrder", ascending: true)
    fetchRequest.sortDescriptors = [orderSort]

    let predicate = NSPredicate(format: "date == %@", date)
    fetchRequest.predicate = predicate

    fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
        managedObjectContext: self.context,
        sectionNameKeyPath: nil,
        cacheName: nil)

    fetchedResultsController.delegate = self

    do {
        try fetchedResultsController.performFetch()
    } catch let error as NSError {
        print("Error: \(error.localizedDescription)")
    }
} 

I tried to pull as much as I could from the answer from a previous post here: Save new order to core data after the using the tableView:moveRowAtIndexPath:toIndexPath: method. Also, I have the canEditRowAtIndexPath function set up and it appears to be functioning properly. Is there anything obvious that I'm messing up in the provided code? Is there an easier solution? Thanks for the support.

0 Answers
Related