Question

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

Can I sort the NSDictionary on basis of key?

 45  40543  45
1 Jan 1970

Solution

 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]];
2010-08-27

Solution

 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:@""];
2015-08-17