How to get the index in Results of a certain Realm object?

梦想的初衷 提交于 2021-02-07 19:14:30

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/34849910/how-to-get-the-index-in-results-of-a-certain-realm-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!