【发布时间】: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