如何获得具有最大ID的商品? [英] How to get item with max id?

查看:31
本文介绍了如何获得具有最大ID的商品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此查询来获取具有最大id的ítem

I'm tryig to get the ítem with max id using this query

realm.objects(Entity).filter("@max.id").first

它抛出一个错误,提示无法解析查询,因此看来这不是正确的方法.

It's throwing an error saying that can't parse query so it seems this is not the correct way to do it.

如何在Realm for Swift上编写此查询?

How can I write this query on Realm for Swift?

推荐答案

仅过滤器无法完成您想要做的事情,因为它们一次只考虑一个顶级对象.

Filters alone cannot do what you're after as they only consider a single top-level object at a time.

除了该概念性问题之外,您发布的代码还存在一些问题:

Beyond that conceptual issue, there are a few issues with the code you posted:

  1. @"@max.id"不是有效的

  1. @"@max.id" is not a valid NSPredicate format string. NSPredicate format strings must be composed of comparisons between expressions, not expressions on their own.

集合运算符(例如@max)必须应用于集合.在您的示例中,它正在应用于Entity.由于Entity不是集合,因此该谓词无效.但是,将集合运算符应用于Entity上的List属性是有效的.

Collection operators such as @max must be applied to a collection. In your example it is being applied to an Entity. Since an Entity is not a collection, the predicate would not be valid. It would be valid to apply a collection operator to a List property on Entity though.

您应该采取的措施如下:

Something like the following should do what you're after:

let entities = realm.objects(Entity)
let id = entities.max("id") as Int?
let entity = id != nil ? entities.filter("id == %@", id!).first : nil

这篇关于如何获得具有最大ID的商品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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