Skip to content
This repository has been archived by the owner on Feb 8, 2022. It is now read-only.

feature request: find indexPath of an object in the results #54

Open
jpaas opened this issue Jan 1, 2016 · 0 comments
Open

feature request: find indexPath of an object in the results #54

jpaas opened this issue Jan 1, 2016 · 0 comments

Comments

@jpaas
Copy link

jpaas commented Jan 1, 2016

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
  }
}
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant