开发者

Core Data distinct count

I would like to have the core data equivalent of the SQL function:

SELECT species, sex, COUNT(*) FROM Bird GROUP BY species, sex;

A request that would typically return this

+---------+------+----------+
| species | sex  | COUNT(*) |
+---------+------+----------+
| Bus     | m    |        2 |
| Car     | f    |        1 |
+---------+------+----------+

with the following entries:

INSERT INTO  Bird VALUES ('BlueBird','Car','f');
INSERT INTO  Bird VALUES ('RedBird','Bus','m');
INSERT INTO  Bird VALUES ('RedBird','Bus','m');

I have suceeded to the distinct request, but I'm having trouble having the count(*). Here is what I have:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Bird" inManagedObjectContext:managedObjectContext];
[request setEntity:entity]; 
[request setReturnsDistinctResults:YES];
[request setResultType:NSDictionaryResultType];
NSDictionary *entityProperties = [e开发者_运维知识库ntity propertiesByName];

NSMutableArray *properties = [NSMutableArray arrayWithObject:[entityProperties objectForKey:@"species"]];
[properties addObject:[entityProperties objectForKey:@"sex"]];
[request setPropertiesToFetch: properties];

What should I add ?


The data model implied by the sample data suggests that you'd have to fetch every object, filter and re-fetch:

NSManagedObjectContext *moc;
NSEntityDescription *birdEntity = [NSEntityDescription entityForName:"Bird" inManagedObjectContext:moc];

NSFetchRequest *fetchAllBirds = [[NSFetchRequest new] autorelease];
[fetchAllBirds setEntity:birdEntity];
NSArray *allBirds = [moc executeFetchRequest:fetchAllBirds error:NULL];

NSArray *species = [allBirds valueForKeyPath:@"@distinctUnionOfObjects.species"];

NSMutableDictionary *speciesCounts = [NSMutableDictionary dictionaryWithCapacity: [species count]];
for (NSString *speci in species)
{
    NSFetchRequest *fetchSpeci = [[NSFetchRequest new] autorelease];
    [fetchSpeci setEntity: birdEntity];
    [fetchSpeci setPredicate:[NSPredicate predicateWithFormat:@"speci == %@", speci]];

    int speciCount = [moc countForFetchRequest:fetchSpeci];
    [speciesCounts setObject:[NSNumber numberWithInt:speciCount] forKey:speci];
}

I'd suggest remodelling the data. You could replace the species attribute with a relationship to a Species entity.

CoreData is not a relational database, it is an object graph persistents framework. If you try and use it as a relational database you'll end up in a mess.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜