4

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?

The reason I need to find out about this is coz I have a UITableView that is set to the sortedPeople, but I need to store the last visible row viewed. The sortedPeople array changes frequently. So, if I can find out the index in the sortedPeople of where the person is, I can create a NSIndexPath and scroll to that row.

dickyj
  • 1,830
  • 1
  • 24
  • 41
  • NSIndexPath consists of 2 values, the row and section. ASFA many do the Alphabet sort in contact list which means you will have number of sections equal to number of unique starting letter of users contacts(Check out system apple contacts app). So as a result you should find not only index in array but also a section. Will you have any alphabet sections in your table view? – Roman Safin Jan 18 '16 at 08:33
  • No, I do not have alphabet sections. And I have spacing between sections, thus I use a section to represent a row, so if I have 10000 persons, I will have 10000 sections. – dickyj Jan 18 '16 at 09:50

1 Answers1

4

you can use indexOf: method to find index of particular object,

try this

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)
Hitendra Solanki
  • 4,871
  • 2
  • 22
  • 29
  • Thx for the answer, will there be a performance issue if the array is large? – dickyj Jan 18 '16 at 09:49
  • 1
    Actually it's optimised by Realm developers, as realm.objects(Person).sorted("id")` returns `Results`, not `Array`. If you want optimise peformance 1) use Instruments at the first place to check if you really need to do so, 2) you can use binary search as the results are sorted. – Michał Ciuba Jan 18 '16 at 12:10