Search code examples
ioscore-datansfetchedresultscontrollernsfetchrequest

Find object index by a property value


On iOS6 coredata, I am trying to build an app similar to slideshow (going through db entities one by one following a specific sequence). That is very easy and I could potentially even use NSFetchedResultsController. Now, the issue is, at certain situations, I would get an entity and I would need to "jump" to that entity without knowing the index of this entity.

One potential solution is loop through the entities one by one. I just wonder if there is another way to get the "index" of this entity. Here is a pseudo code describing the issue:

NSFetchRequest

  • Sorted Entities: desired entity type, order by last update date
  • ** need to find out the index in above list of an entity by entity id or by a unique id.

In SQL, I would do something like

select ROWINDEX
from (
   select ROWNUM as ROWINDEX, uid
   from entity_table
   order by lastupdatedate desc
)
where uid="abc"

Thanks.


Solution

  • I may not be fully understanding you. However. FetchedResultsController has a property .fetchedObjects which is an array. I would think you could readily move around in that array to do whatever you need to.

    You didn't indicate how you wanted to identify the entity you're after; you could certainly use a brute force method as you've suggested to find whatever you're looking for:

    for (NSManagedObject *obj in fetchedResultsController.fetchedObjects)
    {
    
    }
    

    if the result set is small. If the result set is too big for that to be done efficiently, you could try using an NSPredicate to filter the fetchedObjects array, which would probably be preferable. See the link at Using NSPredicate with Core Data NSFetchedResultsController