将NSDictionary键sorting为NSDate
我正在开发一个最新的SDK和XCode 4.2的iOS 4应用程序。
我有一个NSMutableDictionary
其中键是NSDate
和值是NSMutableString
。
当我填补了NSMutableDictionary我想sorting它的键,但我不知道我该怎么做。
我想要一月份的第一个date,然后是二月份,等等。
NSDate
密钥格式是dd / mm / yyyy 。
当NSMutableDictionary
具有所有的键和值时,如何sorting这些键? (我不会添加更多)。
这是一个非常标准的事情,但是,你可能不会sorting NSDictionary – 你可以sorting你从字典中获得的数组。
这是我会做的:
// 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 }
试试这个代码:
NSArray *sortedArray = [[myDict allKeys] sortedArrayUsingSelector:@selector(compare:)];
但请注意,您无法对字典进行sorting,因为它基于键值查找,而不是索引查找。