2011-02-03 1 views
0

数:明確な私は、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]; 

私は何を追加する必要がありますか?

感謝

答えて

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はリレーショナルデータベースではなく、オブジェクトグラフ永続フレームワークです。リレーショナルデータベースとして使用しようとすると、混乱することになります。

+0

あなたの答えはベネディクトです。実際に私はそのようなアルゴリズムについて考えてきましたが、大きなデータセットではそれほど高速ではありません。たぶん私はそれを調整しようとする必要がありますが、私は1つの要求ですべてを得ることが本当に効率的だと思った。 – lorenzo

関連する問題