DeejonZ DeejonZ - 6 months ago 49
Swift Question

UITableView CoreData order with sections

I'm searching around to find some similar scenario but I cannot find anything that contains all features that I need. Looking around I wrote the implementation of the method moveRowAtIndexPath like the following but I have some issue with modifying the reference to the coredata objects so when I click done nothing is saved on coredata.

override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
userDrivenDataModelChange = true;

if (sourceIndexPath == destinationIndexPath) {
return
}

let rooms = fetchedResultsController.sections!

let sourceRoom = rooms[sourceIndexPath.section]
let destinationRoom = rooms[destinationIndexPath.section]

var sourceLights = sourceRoom.objects as! [Light]
var destinationLights = destinationRoom.objects as! [Light]
let light = sourceLights[sourceIndexPath.row]

sourceLights.removeAtIndex(sourceIndexPath.row)
destinationLights.insert(light, atIndex: destinationIndexPath.row)

(destinationLights as NSArray).enumerateObjectsUsingBlock({ object, index, stop in
let light = object as! Light
light.position = index
})

tableView.reloadData()

Utils.saveContext(getAppDelegate().context)

userDrivenDataModelChange = false;
}

Answer

The part that was missing was setting the new room to the item that I was going to move. Something like:

item.relationRoom = <destination room object>

Also it needs some adjustment when you move a light within the same room.