RealmResultsController icon indicating copy to clipboard operation
RealmResultsController copied to clipboard

feature request: find indexPath of an object in the results

Open jpaas opened this issue 10 years ago • 0 comments

I'm sure there are other use cases for this, but here's my current one. I have a list where one item is selected and I have to remember which one it is. So I stash the object id in NSUserDefaults, and every time I fetch my results, I need to know the indexPath of my selected item so I can tell the table it's selected.

For now, I've implemented this extension to do it for me. One method to find it by id, and more general purpose one that can take any NSPredicate to find the first object that matches some condition(s).

In my case, I only have one section, so I'm only searching a single section. Someone else might want to search all sections.

import RealmResultsController

extension RealmResultsController {

  func indexPathOf(sectionIndex: Int, id: AnyObject) -> NSIndexPath? {
    return indexPathOf(sectionIndex, predicate: NSPredicate(format: "id == %@", argumentArray: [id]))
  }

  func indexPathOf(sectionIndex: Int, predicate: NSPredicate) -> NSIndexPath? {
    for row in 0..<numberOfObjectsAt(sectionIndex) {
      let indexPath = NSIndexPath(forRow: row, inSection: sectionIndex)
      let object = objectAt(indexPath)
      if predicate.evaluateWithObject(object as? AnyObject) {
        return indexPath
      }
    }
    return nil
  }
}

jpaas avatar Jan 01 '16 17:01 jpaas