按密钥为NSDate的月份对NSDictionary进行分组和求和

时间:2016-03-07 07:49:42

标签: ios objective-c-blocks nsmutabledictionary ordereddictionary

我有一个具有以下结构的字典,

arrayOne =     {
    "2015-11-09T00:00:00.000Z" = 1;
    "2015-11-16T00:00:00.000Z" = 2;
    "2015-11-23T00:00:00.000Z" = 3;
    "2015-11-30T00:00:00.000Z" = 4;
    "2015-12-07T00:00:00.000Z" = 5;
    "2015-12-14T00:00:00.000Z" = 6;
    "2015-12-21T00:00:00.000Z" = 7;
    "2015-12-28T00:00:00.000Z" = 8;
    "2016-01-04T00:00:00.000Z" = 9;
    "2016-01-11T00:00:00.000Z" = 1;
    "2016-01-18T00:00:00.000Z" = 2;
    "2016-01-25T00:00:00.000Z" = 3;

}

我想创建另一个字典,例如

arrayTWo = {

        "November" = 10;
        "December" = 26;
        "January"  = 15;        
    }

我尝试将日期的月份值放在一个单独的数组中,并将值放在一个单独的数组中,然后尝试在nsmutabledictionary中获取它们,但它没有为重复键赋值,并得到了像

这样的解决方案
arrayTWo = {

    "November" = 4;
    "December" = 8;
    "January"  = 3;        
}

我找不到更好的方法,任何选项都表示赞赏。感谢。

1 个答案:

答案 0 :(得分:1)

试试这个,它使用NSDateFormatter从日期获取月份名称,它根据当前区域设置进行本地化。如果您的语言环境不是英语,您需要取消英语月份名称取消注释该行以明确设置语言环境。

逻辑很简单:

枚举字典,如果密钥(月份)存在,请添加值,如果它没有创建密钥

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];      
formatter.dateFormat = @"MMMM";
// formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSDate *key in arrayOne.allKeys) {
  NSString *month = [formatter stringFromDate:key];
  if (result[month] == nil) {
    result[month] = arrayOne[key];
  } else {
    NSInteger value = [result[month] integerValue];
    result[month] = @(value + [arrayOne[key] integerValue]);
  }
}
NSLog(@"%@", result);