Reputation: 12003
I have a collection of CoreData objects that have a to-many relationship to another object type.
On some of these object I need to search through the related objects to find a particular one. So I loop through them looking for a match which works fine. But on closer inspection I can see CoreData firing off each fault off as it gets to each item in the loop, obviously this is no good - hundreds of faults fired off individually.
Can I trigger CoreData to fire all of the faults in that relationship as a group?
Upvotes: 0
Views: 209
Reputation: 21536
You could use the inverse relationship to "manually" fetch the related objects, using a predicate to restrict the results. For example if Department
has a to-many relationship to Employee
and you want to fetch all the Employees
for currentDepartment
, the fetch might look like this:
NSFetchRequest *employeeFetch = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
employeeFetch.predicate = [NSPredicate predicateWithFormat:@"department == %@",currentDepartment"];
This will fetch the required Employee
objects in one go (*). You could then use either the array returned by the fetch, or the set given by the currentDepartment.employees
relationship to search through. Depending on the complexity of the search you are performing, you might even be able to express it as another clause in the predicate, and avoid the need to loop at all.
(*) Technically, the objects returned by the fetch will still be faults (unless you set returnsObjectsAsFaults
to false), but the data for these faults has been fetched from the store into the cache, so firing the fault will now have minimal overhead.
Upvotes: 1