我正在为iPhone开发一款应用程序,我坚持这一点:
我从对象获取此数据:
{
date = "2014-08-04 11:21:26 +0000";
idChallenger = "-1";
index = "-1";
time = "-1";
},
{
date = "2015-07-31 14:50:40 +0000";
idChallenger = 43;
index = "-1";
time = "-1";
},
{
date = "2015-07-31 16:18:57 +0000";
idChallenger = "-1";
index = "-1";
time = "-1";
},
{
date = "2015-07-31 16:19:29 +0000";
idChallenger = "-1";
index = "-1";
time = "-1";
},
{
date = "2015-08-04 15:25:26 +0000";
idChallenger = "-1";
index = "-1";
time = "-1";
}
现在我应该得到所有日期,按周分组并从最新到最早排序...
此时我坚持使用NSDate组几周,问题在日期多了几年时开始,因为例如结构中的第一个元素按最后一个元素分组。
我该怎么办?感谢
修改:
这是我用来按周分组的代码:
NSMutableArray *weekArray = [NSMutableArray array];
for (int i = 0; i<52; i++) {
[weekArray addObject:[NSMutableArray array]];
}
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:NSCalendarUnitYear | NSCalendarUnitWeekOfYear fromDate:date];
NSMutableArray *innerArray = weekArray[[dateComponents weekOfYear] -1];
[innerArray addObject:dict];
}
for (int i = 0; i<weekArray.count; i++) {
if ([[weekArray objectAtIndex:i] count] > 0) {
NSNumber *iNum = [NSNumber numberWithInt:i+1];
[_mutableDictionary setObject:[weekArray objectAtIndex:i] forKey:iNum];
}
}
_mutableDictionary是:
31 = (
{
date = "2015-07-31 16:19:29 +0000";
idChallenger = "-1";
index = "-1";
time = "-1";
},
{
date = "2015-07-31 16:19:23 +0000";
idChallenger = "-1";
index = "-1";
time = "-1";
},
{
date = "2015-07-31 16:18:57 +0000";
idChallenger = "-1";
index = "-1";
time = "-1";
},
{
date = "2015-07-31 14:50:40 +0000";
idChallenger = 43;
index = "-1";
time = "-1";
}
);
32 = (
{
date = "2015-08-04 15:25:26 +0000";
idChallenger = "-1";
index = "-1";
time = "-1";
},
{
date = "2014-08-04 11:22:40 +0000";
idChallenger = 43;
index = "-1";
time = "-1";
}
);
31和32是一年中的周数
我认为这对我的目标来说是错误的......
在以正确的方式对此NSDate进行分组后,我必须有一个允许我每周在UITableView中创建n个部分的结构
答案 0 :(得分:4)
您需要将分组基于年份和年份。您还需要避免硬编码52个空数组。相反,使用数组字典,其中键表示年份和星期,值是数组。
尝试这样的事情:
NSMutableDictionary *weeksDictionary = [NSMutableDictionary dictionary];
NSCalendar *calendar = [NSCalendar currentCalendar];
for (NSDictionary *dict in _array) {
NSDate *date = [dict objectForKey:@"date"];
NSDateComponents *dateComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitWeekOfYear fromDate:date];
NSInteger year = dateComponents.year;
NSInteger week = dateComponents.weekOfYear;
NSInteger index = year * 100 + week;
NSNumber *key = @(index);
NSMutableArray *weekArray = weeksDictionary[key];
if (!weekArray) {
weekArray = [NSMutableArray array];
weeksDictionary[key] = weekArray;
}
[weekArray addObject:dict];
}
这为您提供了每年/每周都有一个日期的数组。
要在表视图中使用它,请对字典的键进行排序,以便按顺序获取年/周值的数组。然后你可以拆分每个键来获得年份和周:
NSNumber *key = sortedKeysArray[indexPath.section];
NSInteger value = key.integerValue;
NSInteger year = value / 100;
NSInteger week = value % 100;