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)
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?
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With