我有一个DateString数组,其中我有日期,月份和年份的值。
现在我按升序排序了。现在我必须用这个键值对把它放到字典中: -
键 - “1月”(月份名称)和值: - 该月份的日期数组
谁能建议我怎么做?
答案 0 :(得分:0)
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
// Set your year and month here
[components setYear:2016];
NSMutableDictionary *dayAndMonthWiseList = [[NSMutableDictionary alloc] init];
for (int i=1; i<=12; i++)
{
[components setMonth:i];
NSDate *date = [calendar dateFromComponents:components];
NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
NSMutableArray *dayList = [[[NSMutableArray alloc] init] mutableCopy];
for (int j=1; j<=range.length; j++)
{
[dayList addObject:[NSString stringWithFormat:@"%d",j]];
}
[dayAndMonthWiseList setObject:dayList forKey:[NSString stringWithFormat:@"%d",i]];
}
NSLog(@"Dic. :%@",dayAndMonthWiseList);
结果是:
Dic. :{
1 = (
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,
26,
27,
28,
29,
30,
31
);
10 = (
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31
);
11 = (
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30
);
12 = (
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31
);
2 = (
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29
);
3 = (
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31
);
4 = (
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30
);
5 = (
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31
);
6 = (
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30
);
7 = (
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31
);
8 = (
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31
);
9 = (
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30
);
}
答案 1 :(得分:0)
你编写代码,就像每个人都会这样做。
您需要一个将(年,月)映射到(数组)的字典。
你从一个空的可变字典开始。然后你循环你的项目。获取每个项目,获取年份和月份(我假设您不希望一起使用不同年份的Januarys)。在字典中查找年/月,获取可变数组值。如果不存在,请使用新的可变数组作为值添加(年,月)键。所以现在你有一个(年,月)数组,并将项添加到该数组。
如果您的数据在那时被修复,您可以遍历字典并用不可变数组替换所有可变数组(只需使用copy)。而不是首先对所有项目进行排序,只需对字典的键进行排序,因此现在按月和年排序,然后在需要排序时对数组进行排序。例如,在tableview中,您只需要那些实际显示的已排序数组。