¿Cómo puedo reordenar la tabla Realm usando tableview en swift?
Quiero reordenar mi lista de Favoritos en una vista de tabla de forma rápida usando Realm como fuente de datos. El siguiente código funciona, sin embargo, crea una lista de Favoritos dos veces. Estoy luchando por eliminar los datos para poder volver a cargar los favoritos en el orden correcto. Aquí está el código:
//MARK:REORDER list
override func tableView(tableView: UITableView, var moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
let favouritesR = realm.objects(FavouritesRealm)
//convert to array
favouritesArray = []
for min in favouritesR{
favouritesArray.append(min)
}
try! realm.write {
//move the row
let movedObject = self.favouritesArray[sourceIndexPath.row]
favouritesArray.removeAtIndex(sourceIndexPath.row)
favouritesArray.insert(movedObject, atIndex: destinationIndexPath.row)
//here I would like to clear the FavouritesRealm table of all data, so that with the below code I can just read the itmes back in the right order. However, deleting rows crashes the app. See my previous question http://stackoverflow.com/questions/38068826/why-does-clearing-contents-of-realm-table-invalidate-the-object/38095648#38095648
//read the re-ordered list back into the FavouritesReam table
for f in favouritesArray{
let favouriteRealm = FavouritesRealm()
favouriteRealm.name = f.name
favouriteRealm.price = f.price
favouriteRealm.dbSource = f.dbSource
favouriteRealm.date = f.date
favouriteRealm.favourite = f.favourite
realm.add(favouriteRealm)
}
}
}