1
レルムをデータソースとして使用して、迅速にテーブルビューにお気に入りリストを並べ替える必要があります。次のコードは動作しますが、お気に入りのリストを2回作成します。私は正しい順序でお気に入りを再ロードできるようにデータを削除するのに苦労しています。ここでは、コードは次のとおりです。すぐにテーブルビューを使用してレルムテーブルを並べ替える方法
//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)
}
}
}
これは、注文を維持するためにアイテムを削除して領域データベースに戻すのが良いアイデアのようには聞こえません。あなたが望むのは、お気に入り配列をソートし、あなたのオブジェクトにsortOrderプロパティ(単なる整数)を維持することだけです。したがって、レルムからデータをロードしたい場合は、配列を取得し、まずsortOrderごとにソートして、テーブルビューをリロードします。 HTH – Shripada