Sort NSDictionary keys as NSDate

I am developing an iOS 4 application with the latest versions of the SDK and Xcode 4.2.

I have an NSMutableDictionary where the keys are NSDate and the values are NSMutableString .

When I filled out NSMutableDictionary , I want to sort its keys, but I don't know how to do it.

I need the first January dates, then February, etc.

Key format NSDate dd / mm / yyyy .

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

+4
source share
2 answers

This is a pretty standard thing, however you cannot sort the NSDictionary - you can sort the array you get from the dictionary.

This is what I would 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 } 
+8
source

Try this code:

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

But note that you cannot sort the dictionary, as it is based on keyword searches, not indexed searches.

+7
source

Source: https://habr.com/ru/post/1399332/


All Articles