Reputation: 1485
What is the best and most efficient method of fetching the maximum value from an Int column?
Idea A
let maxId = realm.objects(Books).sorted("id").last
Idea B
let maxId = realm.objects(Books).sorted("id", ascending: false).first
Or another idea?
(Yes my code snippets will only return the object with the highest ID, not the actual value)
Upvotes: 12
Views: 4275
Reputation: 352
Swift 4 and Xcode 9.3
I tried ProblemSlover's answer - but it doesn't work anymore...
But give this a try:
let maxValue = realm.objects(Books).max(ofProperty: "id") as Int?
Upvotes: 5
Reputation: 1485
Following on from @ProblemSlover's answer. I created a small app that throws 10000 records into a realm class - calling a function to fetch the max value and using that to set the ID column. I wanted to see some metrics (I ran the test 3 times to get an average). As you can see the MAX function is 2.3 times quicker than sorted/last and nearly 8 times quicker than ascending/first. Sometimes it's just good to know. :)
Upvotes: 23
Reputation: 2537
I believe it should work in the following way
if let maxValue = realm.objects(Books).max("id") as Int?{
// Do some stuff
}
Or just
let maxValue = realm.objects(Books).max("id") as Int?
To make my answer complete I decided to add the code to fetch the min value:
realm.objects(Books).min("id") as Int?
Upvotes: 18