2012-03-02 56 views
4

我正在開發包含最新SDK和XCode 4.2的iOS 4應用程序。將NSDictionary鍵排序爲NSDate

我有一個NSMutableDictionary其中NSDateNSMutableString

當我填滿了NSMutableDictionary我想排序它的鍵,但我不知道我該怎麼做。

我想先要求1月份的日期,然後是2月份等等。

NSDate鍵格式是dd/mm/yyyy

如何在NSMutableDictionary具有其所有的鍵和值時對這些鍵進行排序? (我不會添加更多)。

+0

您不能對一個字典,因爲查找是基於密鑰,而不是指數。您需要先將其轉換爲數組。 – 2012-03-02 07:40:05

+0

從SO的自己的Ole Begemann看到這裏。這個例子是爲了驅動一個表格視圖,但這些原則應該適用於你的案例。 http://oleb.net/blog/2011/12/tutorial-how-to-sort-and-group-uitableview-by-date/ – jrturton 2012-03-02 07:58:58

+0

這可能是一個排序的NSMutableDictionary的實現:http:// cocoawithlove。 com/2008/12/ordereddictionary-subclassing-cocoa.html – VansFannel 2012-03-02 08:24:45

回答

8

這是一個非常標準的事情,但是,你可能不會排序 NSDictionary - 你可以排序你從字典中獲得的數組。

這是我會怎麼做:

// get all keys into array 
NSArray * keys = [your_dictionary allKeys]; 

// sort it 
NSArray * sorted_keys = [keys sortedArrayUsingSelector:@selector(compare:)]; 

// now, access the values in order 
for (NSDate * key in sorted_keys) 
{ 
    // get value 
    NSMutableString * your_value = [your_dictionary valueForKey: key]; 

    // perform operations 
} 
7

試試這個代碼:

NSArray *sortedArray = [[myDict allKeys] sortedArrayUsingSelector:@selector(compare:)]; 

但請注意,你不能排序一個字典,因爲它是基於鍵值查找,沒有索引的查找。

+0

好的。通過這段代碼,我將在另一個數組中對所有的鍵進行排序,然後我可以使用它通過一個命令訪問字典值,不是嗎? – VansFannel 2012-03-02 07:46:41

+1

是的,這是正確的,它的功能就是這樣。 – 2012-03-02 07:48:43