How to get the index in the results of a specific Realm object?

Here is an example.

    class Person: Object {
      dynamic var id
      dynamic var name     
    }

    // does this work?
    let sortedPeople = realm.objects(Person).sorted("id")
    let Dave = realm.objects(Person).filter("id=5")

    // at what index does Dave reside in sortedPeople?

I need to find out about this because I have a UITableView that is set up for sorted people, but I need to save the last visible visible row. The scale of sortedPeople changes frequently. So, if I can find out the index in sorted people where the person is, I can create NSIndexPath and scroll to that line.

+4
source share
1 answer

you can use the method indexOf:to search for the index of a specific object,

try

let sortedPeople = realm.objects(Person).sorted("id")
let Dave = realm.objects(Person).filter("id=5")

//this will return optional Int?
let indexOfDave = sortedPeople.indexOf(Dave)
+2
source

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


All Articles