Search code examples
swiftrealm

Is that possible to use @max in filter in Realm?


I have an Object, say

class Task:Object {
    dynamic var id:Int = 0
    dynamic var name:String = ""

    override func primaryKey() -> String {
        return "id"
    }
}

When I use filter with max.

let tasks = realm.allObjects(ofType: Task.self)
let results = tasks.filter(using: "id.@max")

I got the error:

Unable to parse the format string "id.@max".

Then I realized I should use

let results = tasks.filter(using: "id == id.@max")

Then I got another error:

Terminating app due to uncaught exception 'Invalid predicate', reason: 'Aggregate operations can only be used on key paths that include an array property'

Now I am wondering what can I do if I want to use @max in filter?

I know I could use sorted to get the task with the max id. But I want to know if I could use it with filter.


Solution

  • To retrieve the task with the largest ID, you can do something like the following:

    let tasks = realm.allObjects(ofType: Task.self)
    let id = tasks.maximumValue(ofProperty: "id") as Int?
    let newestTask = realm.object(ofType: Task.self, forPrimaryKey: id)
    

    The reason @max doesn't work for this purpose is that it evaluates to the maximum value of a property for the members of a collection, but the predicate is evaluated in the context of a each individual item.