Sort NSDictionary keys as NSDate

自古美人都是妖i 提交于 2019-12-01 04:32:32

问题


I'm developing an iOS 4 application with latest SDK and XCode 4.2.

I have a NSMutableDictionary where keys are NSDate and values are NSMutableString.

When I have filled up the NSMutableDictionary I want to sort its keys but I don't know how can I do it.

I want first January dates, then February and so on.

The NSDate key format is dd/mm/yyyy.

How can I sort those keys when NSMutableDictionary has all its keys and values? (I'm not going to add more).


回答1:


That's a pretty standard thing, however, you may not sort an NSDictionary - you may sort an array you get from the dictionary however.

This is what I'd do:

// 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
}



回答2:


Try this code:

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

But note that you cannot sort a dictionary, as it is based on key-value lookups, not indexed lookups.



来源:https://stackoverflow.com/questions/9529620/sort-nsdictionary-keys-as-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!