I have an array of IDs: [INT]. Now I want to select all the objects have these ids but need to follow the order of id in the IDs array.
let IDs = [2, 6, 3, 4, 10, 9]
let predicate = NSPredicate(format: "id IN %@", IDs)
let objects = realm.objects(Item.self).filter(predicate)
But in the end, objects was ordered in a different way with IDs. Is there any way that I can sort this objects to the correct order?
You can do it using sort()
:
let IDs = [2, 6, 3, 4, 10, 9]
let predicate = NSPredicate(format: "id IN %@", IDs)
do {
let realm = try Realm()
let objects = realm.objects(Item).filter(predicate).sort({ IDs.indexOf($0.id) < IDs.indexOf($1.id) })
} catch {
}
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