开发者

Core Data count of uniq field

开发者 https://www.devze.com 2022-12-12 06:50 出处:网络
I have model People and model Group开发者_如何学C, People has field of type Group. How I can calculate count of group in people store?

I have model People and model Group开发者_如何学C, People has field of type Group. How I can calculate count of group in people store? Peoples:{name:Mark,group:linktoGroup1},{name:John,group:linktoGroup2},{name:Mike,group:linktoGroup2},{name:Jane,group:linktoGroup1} This people will have 2 group at all.


Given NSSet *setOfPeople,

[setOfPeople valueForKeyPath:@"@distinctUnionOfObjects.group"].count;

is the Key-Value coding way to do it. If there are a lot of people or groups, it may be faster to let the SQLite query engine do it (assuming you're using a SQLite backend)...

In a Core Data query, it's easiest if there is an inverse (to-many) relationship from Group to People. So, if the inverse relationship of People.group is Group.people and you have an initialized NSManagedObjectContext *managedObjectContext]:

NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
[fetch setEntity:[NSEntityDescription entityForName:@"Group" inManagedObjectContext:managedObjectContext]];
[fetch setPredicate:[NSPredicate predicateWithFormat:@"ANY people IN %@", setOfPeople]];

NSError *err;
NSUIntetger groupCount = [managedObjectContext countForFetchRequest:fetch error:&err];
0

精彩评论

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