如何在某个 Realm 对象的结果中获取索引? [英] How to get the index in Results of a certain Realm object?

查看:63
本文介绍了如何在某个 Realm 对象的结果中获取索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个例子.

    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?

我需要了解这一点的原因是因为我有一个设置为 sortedPeople 的 UITableView,但我需要存储查看的最后一个可见行.sortedPeople 数组经常更改.因此,如果我能在该人所在的 sortedPeople 中找到索引,我就可以创建一个 NSIndexPath 并滚动到该行.

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.

推荐答案

您可以使用 indexOf: 方法来查找特定对象的索引,

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

试试这个

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)

这篇关于如何在某个 Realm 对象的结果中获取索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆