Can I sort the NSDictionary
on basis of key?
Asked
Active
Viewed 4.0k times
45
-
1Did the answer provide you the right information? Maybe you can mark it as answer so this question will be marked as solved. – Alex Cio Feb 11 '15 at 11:12
2 Answers
116
You can sort the keys and then create an NSMutableArray
by iterating over them.
NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(compare:)];
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortedKeys)
[sortedValues addObject: [dict objectForKey: key]];

Binarian
- 12,296
- 8
- 53
- 84

Max Seelemann
- 9,344
- 4
- 34
- 40
-
4So is this a correct answer or not? got lots of votes, but no accept? – Just a coder Aug 11 '13 at 10:19
-
This is the correct answer. Sadly, the easier method (in iOS 7) of `[dictionary keysSortedByValueUsingSelector:@selector(compare:)]` doesn't work. For some reason, it gives me results that are almost random in order. I'm wondering if `keysSortedByValueUsingSelector:` does something where it inserts into the array based on the last value of the array, which is kind of useless. – mikeho May 23 '14 at 15:30
-
3@mikeho: The method you mention is way older. But read it aloud: **keys *sorted by value***. It returns the keys of the dictionary when sorting the **value objects** using a selector. It does **not** return the keys sorted by that selector, which is what the code above does. – Max Seelemann May 23 '14 at 19:58
-
@MaxSeelemann: You're right! I misunderstood that. My interpretation of the name was the value of the key, not the value of the actual value associated with the key in the dictionary. – mikeho May 23 '14 at 20:48
-
@mikeho: I can see where you're coming from. However that would be a very inconsistent naming according to Apple's framework standards. Although I realize that method should have rather been called `keysSortedByObjectUsingSelector:` – Max Seelemann May 27 '14 at 08:38
-
@MaxSeelemann: Yeah, I think it's more that it seems like a simple API to return the keys sorted is missing, so that threw me in for a loop. `NSDictionary` should have an API called `keysSortedUsingSelector:` to make things cleaner. – mikeho May 28 '14 at 16:33
-
4The answer should begin by "You can't sort a NSDictionary but..." – Pierre de LESPINAY Aug 05 '14 at 10:16
7
It is much simpler to use objectsForKeys:notFoundMarker:
for that
NSDictionary *yourDictionary;
NSArray *sortedKeys = [yourDictionary.allKeys sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]]];
// As we using same keys from dictionary, we can put any non-nil value for the notFoundMarker, because it will never used
NSArray *sortedValues = [yourDictionary objectsForKeys:sortedKeys notFoundMarker:@""];

Vitalii Gozhenko
- 9,220
- 2
- 48
- 66