I have three models:
+----------+ +--------------+ +------+
| Occasion | <--->> | GiftOccasion | <--->>开发者_开发技巧 | Gift |
+----------+ +--------------+ +------+
I've like to get the name of the occasion, and a count of all the gifts that meet certain criteria. Currently I'm getting the distinct list of occasions sorted by year and name:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request retain];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Occasion" inManagedObjectContext:[self managedObjectContext]];
[request setEntity:entity];
[request setResultType:NSDictionaryResultType];
[request setPropertiesToFetch:[NSArray arrayWithObjects:@"name", @"year", nil]];
[request setReturnsDistinctResults:YES];
NSSortDescriptor *yearDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"year" ascending:NO selector: @selector(caseInsensitiveCompare:)] autorelease];
NSSortDescriptor *nameDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector: @selector(caseInsensitiveCompare:)] autorelease];
NSArray *descriptors = [NSArray arrayWithObjects:yearDescriptor, nameDescriptor, nil];
[request setSortDescriptors:descriptors];
NSError *error = nil;
NSArray *results = [[self managedObjectContext] executeFetchRequest:request error:&error];
... but I'm totally stumped as to how to get the count of Gift
. Is there a straightforward way, or do I need to traverse each GiftOccasion
and related Gift
s and add it all together?
ETA: Note that I'm generating distinct results, here, not getting the model directly. I assume I'd have to run another request to get this information, but if it's possible not to, that would be better.
Thanks!
Get number of objects in a Core Data relationship
This isn't a good answer, and I'm not going to select it as the "right" answer, but what I ended up doing was a ridiculous set of nested NSEnumerator
s that go through each relationship and eventually do a count += 1;
, something like this:
NSUInteger giftCount = 0;
NSEnumerator *oEnum = [resultsList objectEnumerator];
Occasion *occasion = nil;
while (occasion = [oEnum nextObject]) {
NSEnumerator *goEnum = [occasion.giftOccasions objectEnumerator];
GiftOccasion *go;
while (go = [goEnum nextObject]) {
if (go.gifts) {
NSEnumerator *giftEnum = [go.gifts objectEnumerator];
Gift *gift = nil;
while (gift = [giftEnum nextObject]) {
NSLog(@"Gift: %@ %@", gift.name, gift.purchased);
if ([gift.purchased boolValue] == NO) {
giftCount += 1;
}
}
}
}
}
Embarrassing, but it works. :-)
If there is a better, more efficient way to do this, I'd love to hear it. It's one of the things I dislike about Core Data as an ORM vs., say, ActiveRecord.
精彩评论