问题
I want to re-order my list of Favourites in a tableview in swift using Realm as the datasource. The following code works, however, it creates a list of Favourites twice. I am struggling to delete the data in order to be able to re-load the Favourites in the right order. Here is the code:
//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)
}
}
}
回答1:
The most recommended way to manage the order of a list of objects in Realm is to have another Realm object manage it as a List property.
class FavouritesList {
let favourites = List<FavouritesRealm>()
}
This way, you can use the features of the List property itself to manage re-ordering objects, completely within the scope of Realm.
If you don't want to go through the trouble of adding another object, another approach I've used in shipping apps before is to simply add an 'orderedIndex' property that numerically indicates the ordering of the objects, which can then sorted via adding .sorted("orderedIndex") at the end of queries. But the first approach will be much quicker and easier to manage than this way.
来源:https://stackoverflow.com/questions/38112704/how-can-i-re-order-the-realm-table-using-tableview-in-swift