Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by array index using Realm and NSPredicate

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?

like image 307
mashix Avatar asked Oct 20 '15 19:10

mashix


Video Answer


1 Answers

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 {        
}
like image 116
joern Avatar answered Sep 17 '22 20:09

joern