首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >非重复计数

非重复计数
EN

Stack Overflow用户
提问于 2011-02-04 00:05:14
回答 1查看 1.5K关注 0票数 0

我希望拥有与SQL函数等效的核心数据:

代码语言:javascript
复制
SELECT species, sex, COUNT(*) FROM Bird GROUP BY species, sex;

通常会返回以下内容的请求

代码语言:javascript
复制
+---------+------+----------+
| species | sex  | COUNT(*) |
+---------+------+----------+
| Bus     | m    |        2 |
| Car     | f    |        1 |
+---------+------+----------+

具有以下条目:

代码语言:javascript
复制
INSERT INTO  Bird VALUES ('BlueBird','Car','f');
INSERT INTO  Bird VALUES ('RedBird','Bus','m');
INSERT INTO  Bird VALUES ('RedBird','Bus','m');

我已经成功地完成了不同的请求,但我在计数(*)时遇到了问题。这就是我所拥有的:

代码语言:javascript
复制
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];

我应该添加什么?

非常感谢

EN

回答 1

Stack Overflow用户

发布于 2011-02-04 00:29:43

样本数据所隐含的数据模型表明,您必须获取每个对象、过滤和重新获取:

代码语言:javascript
复制
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不是关系数据库,它是一个对象图持久化框架。如果您试图将其用作关系数据库,您将以混乱告终。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4888487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档