I am trying to get the moveRowAtIndexPath method to work using Core Data. My program is user-driven meaning that the user updates the data repeatedly and is basically a table view that displays the name of an Entity. Each Entity has two attributes: a name and an integer that represents its position in the tableView, let's call it orderPosition. I have also created a local variable that stores the lastIndex, which is the number of objects in my array. This allows me to assign an index value to each Entity that I create (last place in table). What I can't manage to figure out is how to use the stored attribute orderPosition in my entity to create a sorted array for the tableView in my View Controller and how to use this to make moveRowAtIndexPath work.
override func viewWillAppear(animated: Bool) {
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDelegate.managedObjectContext!
let fetchReq = NSFetchRequest(entityName: "Object")
objectData = context.executeFetchRequest(fetchReq, error: nil)!
lastIndex = objectData.count
tableView.reloadData()
}
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
let val: AnyObject = self.objectsData.removeAtIndex(sourceIndexPath.row)
self.objectsData.insert(val, atIndex: destinationIndexPath.row)
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDelegate.managedObjectContext!
var fetchReq = NSFetchRequest(entityName: "Object")
fetchReq.predicate = NSPredicate(format: "orderPosition = %@", sourceIndexPath.row)
if let fetchResults = appDelegate.managedObjectContext!.executeFetchRequest(fetchReq, error: nil) as? [NSManagedObject] {
if fetchResults.count != 0{
var managedObject = fetchResults[0]
managedObject.setValue(destinationIndexPath.row, forKey: "orderPosition")
context.save(nil)
}
}
}