我希望拥有与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];我应该添加什么?
非常感谢
发布于 2011-02-04 00:29:43
样本数据所隐含的数据模型表明,您必须获取每个对象、过滤和重新获取:
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不是关系数据库,它是一个对象图持久化框架。如果您试图将其用作关系数据库,您将以混乱告终。
https://stackoverflow.com/questions/4888487
复制相似问题