我希望核心数据等同于SQL函数:
SELECT species, sex, COUNT(*) FROM Bird GROUP BY species, sex;
通常会返回此
的请求+---------+------+----------+
| species | sex | COUNT(*) |
+---------+------+----------+
| Bus | m | 2 |
| Car | f | 1 |
+---------+------+----------+
包含以下条目:
INSERT INTO Bird VALUES ('BlueBird','Car','f');
INSERT INTO Bird VALUES ('RedBird','Bus','m');
INSERT INTO Bird VALUES ('RedBird','Bus','m');
我已经接受了不同的要求,但我在计算(*)时遇到了麻烦。 这就是我所拥有的:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Bird" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
[request setReturnsDistinctResults:YES];
[request setResultType:NSDictionaryResultType];
NSDictionary *entityProperties = [entity propertiesByName];
NSMutableArray *properties = [NSMutableArray arrayWithObject:[entityProperties objectForKey:@"species"]];
[properties addObject:[entityProperties objectForKey:@"sex"]];
[request setPropertiesToFetch: properties];
我应该添加什么?
非常感谢
答案 0 :(得分:1)
示例数据隐含的数据模型表明您必须获取每个对象,过滤并重新获取:
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];
}
我建议重新编码数据。您可以将species
属性替换为与Species
实体的关系。
CoreData不是关系数据库,它是一个对象图持久化框架。如果你尝试将它用作关系数据库,你最终会陷入混乱。