I’m using Core Data; let’s say that I have a many-to-one relationship between employees and departments, and employees are stored in an NSSet in each department. I want to find all the departments that only have one employee. How do I do this with Core Data?
I tried the below code and I get an exception saying that MYEmployee doesn’t respond to allObjects.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.employees.allObjects.count == 1"];
singleEmployeeDepartments = [[myModelController allDepartments] filteredArrayUsingPredicate:predicate]];
First of all, you’re not using Core Data efficiently here, because you are always fetching all departments from the data store and then filtering the resulting array in memory. You can query the managed object context directly for matching departments, instead of fetching all departments, which can reduce memory consumption and might also be faster if you have a lot of departments.
The other key part is to use the
@countoperator in the predicate string to query departments that have a specific number of employees.