基于值嵌套NSDictionary

时间:2015-08-04 16:54:27

标签: ios objective-c uitableview nsdate nsdictionary

我从图书馆返回的数据是:

object

如果我打印_array,那就是结果:

    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:distanceNumber,@"distance",idChallengerN,@"idChallenger",dateFrom, @"date", nil];

[_array addObject:dict];

并且没关系,现在我应该根据周数{ date = "2015-07-31 14:50:40 +0000"; distance = "-1"; idChallenger = 43; }, { date = "2015-07-31 16:18:57 +0000"; distance = "-1"; idChallenger = "-1"; }, { date = "2015-07-31 16:19:05 +0000"; distance = "-1"; idChallenger = "-1"; }, 得到每个date

我试过了:

_array

weekN 根据“日期”返回一年中的星期数,

现在我坚持如何将某些数据分组如果具有相同的周数,例如:

NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];   

for (int i = 0; i<_array.count; i++) {

    NSDictionary *dict = [_array objectAtIndex:i];

    NSDate *date = [dict objectForKey:@"date"];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [calendar components:NSWeekOfYearCalendarUnit fromDate:date];

    NSLog(@"date week = %ld",(long)[dateComponents weekOfYear]);

    NSNumber *weekN = [NSNumber numberWithInteger:[dateComponents weekOfYear]];

    if ([tempDic objectForKey:weekN]) {

       //contains
    }
    else{

      //not contains
    }

感谢popctrl:

weekN = 31 {
  {
  idChallenger = 43;
  idChallenger = 22;
  }
}
weekN = 32 {
  {
  idChallenger = 55;
  idChallenger = 21;
  idChallenger = 678;
  }
}

这段代码产生了非常好的结构,但是如果我想要在一年之前划分几周呢?

1 个答案:

答案 0 :(得分:2)

如果你正在寻找你在帖子底部给出的示例之后的内容,那将是一个数组数组,其中第一个数组按日期索引,内部数组没有特定的顺序。

如果您想保留初始字典数据结构,只需将该数组数组中包含的值设为字典。

编辑:这是我将使用的代码

//To initialize the array
NSMutableArray *weekArray = [NSMutableArray array];

for(int i = 0; i < 52; i++){
    [weekArray addObject:[NSMutableArray array]];
}


//This replaces your for loop
for (int i = 0; i<_array.count; i++) {
    NSDictionary *dict = [_array objectAtIndex:i];

    NSDate *date = [dict objectForKey:@"date"];

    NSCalendar *calendar = [NSCalendar currentCalendar];

    //Notice that I changed NSWeekOfYearCalendarUnit to NSCalendarUnitWeekOfYear, as NSWeekOfYearCalendarUnit has been deprecated
    NSDateComponents *dateComponents = [calendar components:NSCalendarUnitWeekOfYear fromDate:date];

    NSMutableArray *innerArray = weekArray[[dateComponents weekOfYear] - 1];
    [innerArray addObject:dict];
}