Search code examples
objective-ccore-dataentity-relationshipnsfetchedresultscontrollernsfetchrequest

Fetching Core Data related Entities properties


I have two many-to-many related Entities, Customer and City and NSManagedObject subclasses generated from them. I have relationship from Customer to City called cities. In City there is a property called city. Now I am trying to fetch everything from entity Customer with simple fetchResultsController:

-(NSFetchedResultsController *) fetchedResultsController {

  if (_fetchedResultsController != nil)
  {
      return _fetchedResultsController;
  }
  self.managedObjectContext = [[PTDataManager sharedManager] managedObjectContext];
  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  NSEntityDescription *entity = [NSEntityDescription entityForName:@"Customer"
                                            inManagedObjectContext:[self managedObjectContext]];
  [fetchRequest setEntity:entity];

  _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                 managedObjectContext:self.managedObjectContext
                                                                   sectionNameKeyPath:nil
                                                                            cacheName:nil];
  _fetchedResultsController.delegate = self;

  return _fetchedResultsController; 
}

As a result I am retrieving everything fine except cities property ((null) value) with predicate

@"cities.name CONTAINS[cd] %@"

In Customer subclass I can use method:

-(City *)city 
{
  return (CDCities *)[[PTDataFetchHelper sharedInstance] entityForName:@"City"
                                                          withServerID:self.city_server_id
                                                             inContext:[self managedObjectContext]]; 
}

and I am retrieving city-values fine, but this way slows down UI (displaying this data in tableView).
So, questions:

  • if I perform basic fetch like this, am I retrieve values of specified entity only, or values from related entities too?
  • If I need additional predicate, how can I modify it to fetch also city properties from City entity?

Solution

  • A fetch request only fetches one entity type. If you fetch Customer, you get Customers. But you can traverse Core Data relationships without doing additional fetch requests. Just ask any Customer instance for the value of its cities attribute. That will get you zero or more City instances, and you can ask each one of those for its city attribute.

    I'm not sure what you're getting at with @"cities.city [cd]". That's not a predicate. It could be part of a predicate, but it doesn't match the city attribute against anything. It's like one side of an equation.