在NSMutableArray上重复的总和 [英] Sum duplicate on NSMutableArray

查看:60
本文介绍了在NSMutableArray上重复的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSMutableArray对象类型为NSMutableDictionary

NSMutableDictionary包含2个键

-航空公司(字符串)

-评分(整数)

我有一个包含所有对象的NSMutableArray,我需要求和所有航空公司重复对象的等级,例如:

I have an NSMutableArray with all the objects and what i need is to Sum the rating of all the airline companies repeated objects, an example:

Airline  Rating

  A         2

  B         3

  B         4

  C         5

最终结果数组将为A = 2,C = 5,B之和等于7.

The end result array will be the A = 2, C = 5 and the Sum of B´s that is equal to 7.

到目前为止,我的代码:

My code so far:

for (int i = 0; i < arrayMealRating.count; ++i) {
         NSMutableDictionary *item = [arrayMealRating objectAtIndex:i];
         NSLog(@"item=%@",item);
         for (int j = i+1; j < arrayMealRating.count; ++j)
         {
           if ([[item valueForKey:@"Airline"] isEqualToString:[arrayMealRating objectAtIndex:j]]){
                NSMutableDictionary *item = [arrayMealRating objectAtIndex:j];
                NSMutableDictionary *item1 = [arrayMealRating objectAtIndex:i];
                NSInteger auxCount =  [[item valueForKey:@"setMealRating"] integerValue] + [[item1 valueForKey:@"setMealRating"] integerValue];

                NSMutableDictionary *aux = [NSMutableDictionary dictionaryWithObjectsAndKeys:[item valueForKey:@"Airline"], @"Airline"
                                                        ,[NSString stringWithFormat:@"%d",auxCount], @"setMealRating"
                                                        ,nil];
                NSLog(@"aux=%@",aux);
                [arrayMealRating replaceObjectAtIndex:i withObject:aux];

            }
         }
   }

我知道有些混乱,但是我不知道如何使用NSMutableDictionary,任何帮助将不胜感激,在此先感谢!

A bit messy i know but i dont know how to work with NSMutableDictionary, any help will be much appreciated, Thanks in Advance!

推荐答案

如果您不想更改数据存储方式,请使用

Incase you dont want to change how your storing the data, heres how you would do it using key-value coding. Heres the dirrect link to the documentation for @distinctUnionOfObjects and @sum.

// Get all the airline names with no duplicates using the KVC @distinctUnionOfObjects collection operator
NSArray *airlineNames = [arrayMealRating valueForKeyPath:@"@distinctUnionOfObjects.Airline"];

// Loop through all the airlines
for (NSString *airline in airlineNames) {

    // Get an array of all the dictionaries for the current airline
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(Airline == %@)", airline];
    NSArray *airlineMealRating = [arrayMealRating filteredArrayUsingPredicate:predicate];

    // Get the sum of all the ratings using KVC @sum collection operator
    NSNumber *rating = [airlineMealRating valueForKeyPath:@"@sum.Rating"];
    NSLog(@"%@: %@", airline, rating);
}

这给出了以下输出

A: 2
B: 7
C: 5

这篇关于在NSMutableArray上重复的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆