Conceptually, NSDictionary is unsorted, as C0deH4cker has already said.
If you need an order, you can either write the keys to an array (but you may have problems saving the array after the key has been removed from the dictionary, but there are tutorials on how to create an un-keeping array using CFArray ) or NSSortedSet .
Or you can subclass NSDictionary - not very trivial, since NSDictionary is a cluster of classes. But, fortunately, Matt shows in his fantastic blogpost "OrderedDictionary: Subclassification of Cocoa Class Cluster" , how to use a little trick, relationship.
Please note that your code
NSArray* sortedKeys = [stats keysSortedByValueUsingComparator:^(id first, id second) { if ( first < second ) { return (NSComparisonResult)NSOrderedAscending; } else if ( first > second ) { return (NSComparisonResult)NSOrderedDescending; } else { return (NSComparisonResult)NSOrderedSame; } }];
doesn't do what you want as you apply C-statements to objects. Now their pointers will be ordered.
it should be something like
NSArray* sortedKeys = [stats keysSortedByValueUsingComparator:^(id first, id second) { return [first compare:second]; }];
or if you want to order scalars that are wrappers as objects (i.e. NSNumber)
NSArray* sortedKeys = [stats keysSortedByValueUsingComparator:^(id first, id second) { if ([first integerValue] > [second integerValue]) return (NSComparisonResult)NSOrderedDescending; if ([first integerValue] < [second integerValue]) return (NSComparisonResult)NSOrderedAscending; return (NSComparisonResult)NSOrderedSame; }];
vikingosegundo
source share