开发者

How to use NSPredicate to filter based on child elements?

开发者 https://www.devze.com 2023-03-06 12:12 出处:网络
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开发者_如何学JAVA find all

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开发者_如何学JAVA 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.

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];

The other key part is to use the @count operator in the predicate string to query departments that have a specific number of employees.

0

精彩评论

暂无评论...
验证码 换一张
取 消