如何使用Realm排序? [英] How to sort using Realm?

查看:228
本文介绍了如何使用Realm排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何使用Realm进行排序.我当前的代码是.

I don't know how to sort using Realm. My current code is.

data = realm.objects(WorkoutSet)
data = data!.sorted("date")

我想将日期Int从高数字到低数字进行排序.文档需要更多信息,并且GitHub链接会引发404消息.

I want to sort date an Int from high numbers to low numbers. The docs need more information and the GitHub link throws a 404 message.

推荐答案

您可以在sorted方法中添加ascending参数:

You can add an ascending parameter to the sorted method:

data = data!.sorted("date", ascending: false)

这会使用日期字段按降序对您的WorkoutSet进行排序.

This sorts your WorkoutSet using the date field in descending order.

更新

使用Swift 3和最新的RealmSwift版本,现在已更改为:

With Swift 3 and the latest RealmSwift version this has now changed to:

data = data!.sorted(byKeyPath: "date", ascending: false)

如果您想自己评估排序标准,可以使用:

If you want to evaluate the sort criteria yourself you could use:

data = data!.sorted(by: { (lhsData, rhsData) -> Bool in
   return lshData.something > rhsData.something
})

但是请注意,您自己对结果进行排序的确会返回Array而不是Realm Results对象.这意味着会有性能和内存开销,因为Results是惰性的,如果使用上述方法进行排序,您将失去这种惰性行为,因为Realm必须评估每个对象!您应尽可能坚持执行结果.仅在确实没有其他方法可以对项目进行排序时,才使用上述方法.

But be aware that sorting your results by yourself does return an Array instead of a Realm Results object. That means there will be a performance and memory overhead, because Results is lazy and if do the sorting with the above method you will lose that lazy behavior because Realm has to evaluate each object! You should stick to Results whenever possible. Only use the above method if there really is no other way to sort your items.

这篇关于如何使用Realm排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆