2015-06-10 34 views
2

我有一本有許多道具的字典。我希望按日期順序升序。我的日期格式是: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更大,我想從方法只採取true1

+0

您正在使用冒泡排序,這非常慢。使用適當的Cocoa方法。你還創建了約數^ 2/2的NSDateFormatters,這又非常慢。和「但沒有工作」:你是什麼意思? – gnasher729

+0

我不能使用可可方法。如果我使用可可方法,他只排列日期組件,但我需要按日期排序所有字典項目。所以我需要知道變化的位置 –

+0

字典是**無序**。您可以對數組進行排序,但不能對字典進行排序。 – johnpatrickmorgan

回答

5

NSMutableArray手柄使用其分類方法之一進行分類(例如sortUsingComparator:):

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"dd-MMM-yyyy HH:mm:ss"]; 

[aux sortUsingComparator:^NSComparisonResult(NSString *datestring1, NSString *datestring2) { 
    NSDate *date1 = [dateFormatter dateFromString:datestring1]; 
    NSDate *date2 = [dateFormatter dateFromString:datestring2]; 
    return [date1 compare:date2]; 
}]; 

SIDENOTE:您還應該考慮將日期字符串轉換爲NSDate s 一次並將它們作爲NSDate s存儲在您的數組中。

+0

以及如何在一個條件下如何使用它? –

+0

你現在明白了嗎? –

+0

不是很好。 06-Oct-2014 12:48:07, 10-Jun-2015 00:00:00, 10-Jun-2015 03:08:00, 10-Jun-2015 03:09:00, 10- Jun-2015 03:09:00, 10-Jun-2015 07:46:00, 10-Jun-2015 08:00:00, 10-Jun-2015 09:27:11, 10-Jun- 2015 10:00:00, 2015年6月9日18時20分00秒, 09-Jun-2015 17:20:00, 2015年9月9日17:14:00, 2015年6月9日16 :14:00, 2014年10月20日13:36:53, 2014年10月18日16:23:26, 2014年10月17日17:00:51, 2014年10月12日12:57 :55, 14-Oct-2014 12:08:33, 14-Oct-2014 12:31:06, 03-Oct-2014 16:31:06, 10-Jun-2015 00:00:00, 10-Jun-2015 07:25:48, 10-Jun-2015 08:18:06, 10 -Jun-2015 09:23:49, 10-Jun-2015 11:02:28, 這是返回你的鱈魚。 –

0

假設你有一個字段「的startDate」對象類型的NSDate然後使用下面的代碼的一個NSMutableArray:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"startDate" ascending:YES]; 
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; 
0

嘗試比較和填充如下圖所示

NSComparisonResult result; 
    result = [Str_StoreOpening compare:Str_StoreClosing]; // comparing two dates 

    NSString *Str_CloseTime; 
    if(result==NSOrderedAscending){ 
     //populate in Ordered Ascending in here 

    }else if(result==NSOrderedDescending){ 
     //populate in Ordered Descending in here 


    }else{ 
     //NSLog(@"Both dates are same"); 

    }