Swift+Realm1.0.1+Alamofire(二)

2016-07-12  本文已影响62人  童星

Q:怎么交换或者移动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顺序,然后再更新数据库即可

上一篇下一篇

猜你喜欢

热点阅读