这就是我所拥有的:
一个NSMutableArray
,包含多个NSDictionary
个对象。
每个NSDictionary
都有一个日期字符串作为元素。
这是我的循环,在每个NSDictionary
[dateFormatterIn setDateFormat:@"yyyyMMddHHmmss\n"];
[dateFormatterOut setDateFormat:@"dd.MM.yyyy"];
for(NSMutableDictionary *thisStory in stories){
id fromDate = [thisStory objectForKey:@"from_time"];
id date = [dateFormatterIn dateFromString:fromDate];
NSLog(@"%@", [dateFormatterOut stringFromDate:date]);
}
有没有人知道如何按日期对数组stories
进行排序?
我对客观C很新。
提前谢谢!
答案 0 :(得分:5)
使用你的故事数组排序使用描述性方法可以解决这个问题:
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"from_time" ascending: YES] autorelease];
[stories sortUsingDescriptors: [NSArray arrayWithObject: sortDescriptor]];
答案 1 :(得分:0)
让我们假设以下数据结构:数组变量名: collectionArray =
[
{
date: "01-02-2015 02:01",
value: 1,
name: "rajan"
},
{
date: "01-02-2014 02:01",
value: 11,
name: "rajan1"
},
{
date: "01-02-2012 02:01",
value: 111,
name: "rajan2"
}
]
现在按日期对nsdictionary数组进行排序,我们按照以下步骤进行操作
`NSDateFormatter * formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@“dd-MM-yyyy HH:mm”];
NSMutableArray *sortedArray = [[collectionArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
NSString *d1Str =[obj1 valueForKey:@"date"];
NSString *d2Str =[obj2 valueForKey:@"date"]
NSString *d1Timestamp = [NSString stringWithFormat:@"%f", [[formatter dateFromString:d1Str] timeIntervalSince1970]];
NSString *d2Timestamp = [NSString stringWithFormat:@"%f", [[formatter dateFromString:d2Str] timeIntervalSince1970]];
return [d2Timestamp compare:d1Timestamp options:NSNumericSearch]; // descending order
}] mutableCopy];`