0

カテゴリと金額の値をコア データに保存しています。上位 5 つのカテゴリをユーザーに表示したいです。結果を取得することはできますが、同様のカテゴリの金額を合計して上位 5 を表示するにはどうすればよいですか?

カテゴリの金額を合計するためのロジックをいくつか試しましたが、そこで立ち往生しており、それが正しいかどうかも知りたいです。

  NSArray *results = [moc executeFetchRequest:request error:&error];
for(int i = 0; i < [results count] ; i ++){
    double sum = 0;
    NSString *temp = [[results objectAtIndex:i]valueForKey:@"category"];
    for( int j = 0; j< [results count] ; j ++){
        if([temp isEqualToString:[[results objectAtIndex:j]valueForKey:@"category"]]){
            sum = sum + [[[results objectAtIndex:j]valueForKey:@"amount"]doubleValue];
        }
    }
NSLog(@"%f",sum);
NSLog(@"%f",temp);

    }
}
4

3 に答える 3

0

結果の合計は、昇順または降順で配列に格納できます。その配列から、インデックスから上位 5 つの合計を表示できます。

あなたより

于 2013-03-15T10:10:31.420 に答える
0

コアデータから値を取得すると、次を使用して重複値を検証できます

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"amount=%d",previousValueotNot];

次に、このコードを以下に追加します

    [request setPredicate:predicate];
NSError *error;
    NSArray *tempResults = [context executeFetchRequest:request error:&error];
    NSLog(@"temparray coun is %d",[tempResults count]);
if ([tempResults count] > 0)
    {

       //sum here the duplicates.
       //sample code is 


NSArray *tempResults = [self.managedObjectContext executeFetchRequest:request error:&error];
NSMutableArray *tempBudsArray = [[NSMutableArray alloc] init];
for ( Favorite *fav in tempResults) 
    {
      //.. Here u get the values from the core data and sum here  ,then store all the values, later u can put in ascending order
    }


 }
于 2013-03-15T10:20:19.947 に答える
0

あなたが望むのはカウントされたセットです。ドキュメントはこちら: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSCountedSet_Class/Reference/Reference.html 基本的に、持っているすべてのオブジェクトを入れてから、オブジェクトの数を求めます。カウントされたセットは、特定のアイテムがセット内にある回数を返します。-countForObjectの代わりに必ず使用してください-count。楽しむ

于 2013-03-15T10:08:54.587 に答える