Swift+Realm1.0.1+Alamofire(二)

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顺序,然后再更新数据库即可

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容