Search code examples
core-dataios4nsfetchrequestrelationships

Core Data Relationship shown in tableView


I am developing an application with a tableview showing the content of a core data table. The datamodel is something like this: Entity(name, code)->>Translation(text, code)

I retrieve all the entities using the usual NSFetchedResultsController, but then once is time to populate each row (through tableview cellForRowAtIndexPath:) I have to dive into each entity to retrieve 2 translations based on the code inputed by the user. I am using a NSFetchRequest to do that but I was wondering if it is the right thing to do (one fetch request each time I populate a row). Instinctively I would retrieve all the data I need in the NSFetchedResultsController, instead of searching for each translation each time I populate a cell, but I cannot figure out how. Do anyone has some advice, or maybe some interesting links?


Solution

  • If each cell must display the Translation objects related to each Entity object, then you only need to walk the relationship from the fetched Entity object to the appropriate Translation objects.

    Once you've fetched the Entity objects and then structured the table to display them, then to access the values in the translations for each cell row like so:

    NSSet *translations=[anEntityObject valueForKey:@"translations"];
    

    ... which returns a set of Translation object for the Entity object represented by the tableview row.

    As a very general rule, you only do one fetch per tableview. A table view should be configured to display data related to one particular entity.