Q:怎么交換或者移動(dòng)realm數(shù)據(jù)庫里面的兩條記錄呢灶?
- 需求:
我要移動(dòng)cell或者交換cell上的兩條數(shù)據(jù)模型吴超,下次展示這個(gè)頁面以我現(xiàn)在更改的順序出現(xiàn)。 - 思路:
因?yàn)閿?shù)據(jù)是從網(wǎng)絡(luò)獲取鸯乃,然后更新數(shù)據(jù)庫鲸阻,然后讀取出來跋涣,所以要想改變順序只有兩種方法:
1.對(duì)查詢結(jié)果按照自己想要的查詢條件進(jìn)行排序,但是這樣好像每次都需要對(duì)其查詢操作鸟悴,顯然不是太好陈辱。
2.直接對(duì)realm數(shù)據(jù)庫里面的記錄進(jìn)行移動(dòng)或者交換,于是去查詢r(jià)ealm的源代碼细诸,發(fā)現(xiàn)了兩個(gè)方法:
移動(dòng)和交換
具體實(shí)現(xiàn)方法如下:
/**
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數(shù)據(jù)庫因?yàn)槭菬o序的沛贪,但是它提供了一個(gè)List
類型的集合(關(guān)于List的介紹可以去看官方文檔),被加入到List
集合中的Object
可以保證有序的插入震贵,所以利赋,假如我要改變文章ArticleDAO
模型的展示順序,那么我可以新建一個(gè)ArticleDAOList
模型猩系,然后添加:
let list = List<ArticleDAO>()
來存放ArticleDAO
媚送,這樣ArtucleDAO
的插入順序就可以保證了,將ArticleDAOList
寇甸,存入數(shù)據(jù)庫塘偎。如果需要更改順序,那么直接更新ArticleDAOList
順序拿霉,然后再更新數(shù)據(jù)庫即可