Sort by array index using Realm and NSPredicate

I have an array of identifiers: [INT]. Now I want all the objects to have these identifiers, but must follow the order id in the ID 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, the objects were ordered differently with identifiers. Is there a way to sort these objects in the correct order?

+5
source share
2 answers

You can do this 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 { } 
+5
source

In Realm Results conforms to the RealmCollectionType protocol, which has a sorted(_:) function. This function accepts a sequence of SortDescriptor s that are StringLiteralConvertible , which makes them pretty easy to use:

 let realm = try! Realm() let IDs = [2, 6, 3, 4, 10, 9] let objects = realm.objects(Item).filter("id IN %@", IDs).sorted(["id"]) 
-1
source

Source: https://habr.com/ru/post/1234150/


All Articles