如何在swift中使用tableview重新排序Realm表

时间:2016-06-30 01:47:51

标签: swift uitableview realm

我想使用Realm作为数据源在swift的tableview中重新排序我的收藏夹列表。以下代码有效,但它会创建两次收藏夹列表。我正在努力删除数据,以便能够以正确的顺序重新加载收藏夹。这是代码:

//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 个答案:

答案 0 :(得分:1)

管理Realm中对象列表顺序的最佳推荐方法是让另一个Realm对象将其作为List属性进行管理。

class FavouritesList {
   let favourites = List<FavouritesRealm>()
}

这样,您可以使用List属性本身的功能来管理重新排序对象,完全在Realm的范围内。

如果您不想在添加其他对象时遇到麻烦,我之前在发布应用时使用的另一种方法就是简单地添加一个“有序指数”&#39;以数字方式指示对象排序的属性,然后可以通过在查询结尾添加.sorted("orderedIndex")进行排序。但是第一种方法比这种方式更快更容易管理。