How To Sort Using Realm?
I don't know how to sort using Realm. My current code is.
data = realm.objects(WorkoutSet)
data = data!.sorted("date")
I want to sort date an Int
from high numbers to low numbers. The docs need more information and the GitHub link throws a 404
message.
Answer
You can add an ascending
parameter to the sorted
method:
data = data!.sorted("date", ascending: false)
This sorts your WorkoutSet using the date field in descending order.
Update
With Swift 3 and the latest RealmSwift version this has now changed to:
data = data!.sorted(byKeyPath: "date", ascending: false)
If you want to evaluate the sort criteria yourself you could use:
data = data!.sorted(by: { (lhsData, rhsData) -> Bool in
return lshData.something > rhsData.something
})
But be aware that sorting your results by yourself does return an Array
instead of a Realm Results
object. That means there will be a performance and memory overhead, because Results
is lazy and if do the sorting with the above method you will lose that lazy behavior because Realm has to evaluate each object! You should stick to Results whenever possible. Only use the above method if there really is no other way to sort your items.
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → I can't do a foreign key, constraint error
- → Setting a default value on settings form return null in Octobercms
- → Eloquent Multitable query
- → "Laravel 5.1" add user and project with userId
- → Image does not go in database with file name only tmp name saved?
- → Database backup with custom code in laravel 5 and get the data upto 10 rows from per table in database
- → Trait 'IlluminateFoundationBusDispatchesJobs' not found
- → Setting the maxlength of text in an element that is displayed
- → laravel check between 2 integer from database
- → how to retrieve image from database in laravel 5.1?
- → relationship for database Column type object
- → Carousel in Laravel 4 does not show as expected