【问题标题】:how can I re-order the Realm table using tableview in swift如何在 swift 中使用 tableview 重新排序 Realm 表
【发布时间】:2016-06-30 01:47:51
【问题描述】:

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

//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 属性(只是一个整数)。因此,每当您想从 Realm 加载数据时,请先获取数组,然后根据 sortOrder 对其进行排序,然后重新加载表视图。 HTH

标签: swift uitableview realm


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    相关资源
    最近更新 更多