This is something i just can’t figure out working with Core Data. I want to work with an NSFetchedResultsControllerDelegate and the usual code i’ve seen so far is easy to understand but always based on a one entity model. So you want to show in your table all the “events”, you do a fetch request on the Event entity and there, you are set to go.
The thing is, my model is:
City (one-to-one) Company (one-to-many) Employees
My table would need to show the employees, but the fetch would have to be based on the City, in order to retrieve the Company and then the Employees, right? I’m completely lost at this, i just don’t see how to do the fetch.
Because if i fetch City or Company and i put Employees in an NSMutableSet, don’t i loose all the authomatic UITableViewController syncing? For instance, if i do it like this, i will be unable to do something like
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo =
[[_fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
You data model should have reciprocal relationships such that when you fetch any particular object, you have immediate access to all related objects.
In your case, a data model with reciprocal relationships would look something like:
So, if you have an
Employeeobject, you find the company withself.companyand the city byself.company.city(in most case the actualselfis unnecessary and I use it for illustration purposes.) If you have aCompanyobject, you find employees inself.employeesand the city inself.city. If you have aCityobject you would find all the employees withself.company.employees.Relationships are what actually create the object graph at the heart of Core Data. You use fetches to find one group of objects in the graph and then you “walk” the relationships outward from those objects to find all the related data. It is the reciprocal relationships that make it possible to go back and forth across the relationships in both directions.