Can i sort the NSDictionary on basis of key in Objective-C?

suse picture suse · Aug 27, 2010 · Viewed 38.4k times · Source

Can I sort the NSDictionary on basis of key?

Answer

Max Seelemann picture Max Seelemann · Aug 27, 2010

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