我试图用这个查询来获得带有最大id的系统
realm.objects(Entity).filter("@max.id").first它抛出一个错误,说无法解析查询,所以看起来这不是正确的方法。
如何在Realm for Swift上编写此查询?
I'm tryig to get the ítem with max id using this query
realm.objects(Entity).filter("@max.id").firstIt's throwing an error saying that can't parse query so it seems this is not the correct way to do it.
How can I write this query on Realm for Swift?
最满意答案
单独使用过滤器无法实现您所追求的目标,因为它们一次只考虑一个顶级对象。
除了这个概念问题之外,您发布的代码还存在一些问题:
@"@max.id"不是有效的NSPredicate格式字符串 。 NSPredicate格式字符串必须由表达式之间的比较组成,而不是由表达式组成。
必须将@max等集合运算符应用于集合。 在你的例子中,它被应用于一个Entity 。 由于一个Entity不是一个集合,所以谓词是无效的。 不过,将集合运算符应用于Entity上的List属性将是有效的。
像下面这样的东西应该做你以后的事情:
let entities = realm.objects(Entity) let id = entities.max("id") as Int? let entity = id != nil ? entities.filter("id == %@", id!).first : nilFilters 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:
@"@max.id" is not a valid NSPredicate format string. NSPredicate format strings must be composed of comparisons between expressions, not expressions on their own.
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更多推荐
发布评论