【发布时间】:2015-06-10 10:03:25
【问题描述】:
我有一本包含许多项目的字典。我想按日期排序升序项目。我的日期格式是:10-Jun-2015 09:27:11
我试过这段代码但没有用:aux 是我的带有日期组件的数组。
for (int i=0; i<aux.count-1; i++) {
for (int j=i+1; j<aux.count; j++) {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd-MM-yyyy hh:mm:ss"];
NSDate *date1 = [dateFormat dateFromString:[aux objectAtIndex:i]];
NSDate *date2 = [dateFormat dateFromString:[aux objectAtIndex:j]];
NSComparisonResult comparisonResult = [date1 compare:date2];
if (comparisonResult==-1) {
NSString *var= [aux objectAtIndex:i];
[aux replaceObjectAtIndex:i withObject:[aux objectAtIndex:j]];
[aux replaceObjectAtIndex:j withObject:var];
}
}
}
我想比较两个日期(date1,date2)。如果 date2 像 date1 一样大,我想交换。我想手动进行交换:如果 date2 更大,我只想从方法中获取 true 或 1。
【问题讨论】:
-
您正在使用冒泡排序,这非常慢。使用正确的 Cocoa 方法。您还创建了大约 count^2 / 2 NSDateFormatters,这又非常慢。还有“但没用”:你的意思是什么?
-
我不能使用可可方法。如果我使用可可方法,他只订购带有日期组件的数组,但我需要按日期订购所有字典项目。所以我需要知道改变的位置
-
字典是无序的。您可以对数组进行排序,但不能对字典进行排序。
-
我知道。因此,当我在数组中与日期组件 objectatindex:1 和 objectatindex:2 互换时,我将更改所有项目。我的字典由许多数组组成。
-
你检查我的答案了吗
标签: ios objective-c date