core-datansfetchedresultscontrollerfetched-property

core data fetched properties and NSFetchedResultsController


I read this in the core data programming guide:

In many cases, your initial fetch retrieves a starting node in the object graph and thereafter you do not execute fetch requests, you simply follow relationships.

This makes sense if everything is linked to one object.

However, say i have this object model and relationship

Company (one to many) Team (one to many) Employee (one to one) Role

Say I load my Company at the start with a fetch request. I then have access to a set of Teams, and in each Team i have a set of Employees.

(this is all hypothetical, but my app follows the same model)

I want to load a UITableView that lists all Employees which have a Role of 'developer', and I want to do this using an NSFetchedResultsController.

I would like to create a fetched property on Company that returns all 'developers'. Which is easy enough.

How would I link this fetched property to NSFetchedResultsController ?


Solution

  • I am not sure I understood your question, but if you want to use a NSFetchedResultsController with UITableView you have to use a NSFetchRequest, you cannot just follow relationship, which is use faulting.

    It seems you already have a fetch request, for use it with a fetched controller you have to pass such request to the NSFetchedResultsController.

    However you can get NSFetchedPropertyDescription by looking into the entity description, and its properties:

    NSEntityDescription *entityDescription = .....
    

    Then you can call properties and cycle all the array until you find your property:

    NSArray *allProperties = entityDescription.properties;
    NSFetchedPropertiesDescription *myPropertyDescription;
    for(NSPropertyDescription *propertyDescription in allProperties) {
      // find it by name or class
      if([propertyDescription isKindOfClass:[NSFetchedPropertyDescription class]])
        myPropertyDescription = (NSFetchedPropertyDescription*)propertyDescription;
    }
    
    NSFetchedRequest *fetchRequest = [myPropertyDescription fetchRequest];
    
            NSFetchedResultsController *myController = [[NSFetchedResultsController alloc]
                                                     initWithFetchRequest:fetchRequest
                                                     managedObjectContext:myManagedObjectContext
                                                     sectionNameKeyPath:nil
                                                     cacheName:myCacheName];
    

    I do not have my Mac right now so I cannot test for code validity, however it should be right.