How to use NSPredicate to filter based on child elements?

I am using Core Data; let's say that I have a one-to-one relationship between employees and departments, and employees are stored NSSetin each department. I want to find all departments in which there is only one employee. How to do it using Core Data?

I tried the code below and I get an exception saying that MYEmployee is not responding allObjects.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.employees.allObjects.count == 1"];
singleEmployeeDepartments = [[myModelController allDepartments] filteredArrayUsingPredicate:predicate]];
+3
source share
1 answer

, Core Data , . , , , , , .

NSManagedObjectContext *moc = ...;
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"Department" inManagedObjectContext:moc]];
[request setPredicate:[NSPredicate predicateWithFormat:@"employees.@count == 1"]];
NSArray *singleEmployeeDepartments = [moc executeFetchRequest:request error:NULL];

@count , .

+7

All Articles