按照NSDate对NSDictionary的键进行排序

4
我正在使用最新的SDK和XCode 4.2开发一个iOS 4应用程序。
我有一个NSMutableDictionary,其中键是NSDate,值是NSMutableString。
当我填充了NSMutableDictionary后,我想对其键进行排序,但我不知道如何做。
我希望首先是1月份的日期,然后是2月份等等。
NSDate键的格式为dd/mm/yyyy。
在NSMutableDictionary具有所有键和值时,如何对这些键进行排序?(我不会再添加更多内容。)

你不能对字典进行排序,因为查找是基于键而不是索引。你需要先将其转换为数组。 - Richard J. Ross III
请参考 Stack Overflow 上的 Ole Begemann 所提供的内容。该示例是用于操作表视图的,但这些原则也适用于您的情况。 http://oleb.net/blog/2011/12/tutorial-how-to-sort-and-group-uitableview-by-date/ - jrturton
这可能是一个已排序的NSMutableDictionary的实现:http://cocoawithlove.com/2008/12/ordereddictionary-subclassing-cocoa.html - VansFannel
2个回答

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:)];

请注意,字典是基于键值查找而不是索引查找的,因此无法对其进行排序。


好的。通过这段代码,我将在另一个数组中拥有所有排序后的键,然后我可以使用它按顺序访问字典值,是吗? - VansFannel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接