How to get item with max id?

蹲街弑〆低调 提交于 2019-12-21 20:11:20

问题


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.

How can I write this query on Realm for Swift?


回答1:


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" is not a valid NSPredicate format string. NSPredicate format strings must be composed of comparisons between expressions, not expressions on their own.

  2. 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



回答2:


I'm using Xcode 8.0 and Swift 3.0

Following worked for me:

let allEntries = realm.objects(Model.self)
if allEntries.count > 0 {
    let lastId = allEntries.max(ofProperty: "id") as Int?
    return lastId! + 1
} else {
    return 1
}



回答3:


Swift 4 and Xcode 9.3

if let personWithMaxAge = realm.objects(Person.self).max(by: { $0.age > $1.age }) {
    print(personWithMaxAge.age)
}


来源:https://stackoverflow.com/questions/32804266/how-to-get-item-with-max-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!