Q:怎么交换或者移动realm数据库里面的两条记录?
- 需求:
我要移动cell或者交换cell上的两条数据模型,下次展示这个页面以我现在更改的顺序出现。 - 思路:
因为数据是从网络获取,然后更新数据库,然后读取出来,所以要想改变顺序只有两种方法:
1.对查询结果按照自己想要的查询条件进行排序,但是这样好像每次都需要对其查询操作,显然不是太好。
2.直接对realm数据库里面的记录进行移动或者交换,于是去查询realm的源代码,发现了两个方法:
具体实现方法如下:
/**
Replaces an object at the given index with a new object.
- warning: This method may only be called during a write transaction.
- warning: This method will throw an exception if called with an invalid index.
- parameter index: The index of the object to be replaced.
- parameter object: An object.
*/
public func move(from from: Int, to: Int) { // swiftlint:disable:this variable_name
throwForNegativeIndex(from)
throwForNegativeIndex(to)
_rlmArray.moveObjectAtIndex(UInt(from), toIndex: UInt(to))
}
/**
Exchanges the objects in the list at given indices.
- warning: This method may only be called during a write transaction.
- warning: This method will throw an exception if called with invalid indices.
- parameter index1: The index of the object which should replace the object at index `index2`.
- parameter index2: The index of the object which should replace the object at index `index1`.
*/
public func swap(index1: Int, _ index2: Int) {
throwForNegativeIndex(index1, parameterName: "index1")
throwForNegativeIndex(index2, parameterName: "index2")
_rlmArray.exchangeObjectAtIndex(UInt(index1), withObjectAtIndex: UInt(index2))
}
使用:
realm数据库因为是无序的,但是它提供了一个List
类型的集合(关于List的介绍可以去看官方文档),被加入到List
集合中的Object
可以保证有序的插入,所以,假如我要改变文章ArticleDAO
模型的展示顺序,那么我可以新建一个ArticleDAOList
模型,然后添加:
let list = List<ArticleDAO>()
来存放ArticleDAO
,这样ArtucleDAO
的插入顺序就可以保证了,将ArticleDAOList
,存入数据库。如果需要更改顺序,那么直接更新ArticleDAOList
顺序,然后再更新数据库即可
网友评论