Can I sort the NSDictionary
on basis of key?
The NSDictionary class declares the programmatic interface to objects that manage immutable associations of keys and values. For example, an interactive form could be represented as a dictionary, with the field names as keys, corresponding to user-entered values.
The trick to sorting an array is a method on the array itself called "sortedArrayUsingDescriptors:". The method takes an array of NSSortDescriptor objects. These descriptors allow you to describe how your data should be sorted.
NSDictionary / NSMutableDictionary copies keys, and holds strong references to values. NSMapTable is mutable, without an immutable counterpart. NSMapTable can hold keys and values with weak references, in such a way that entries are removed when either the key or value is deallocated.
An NSDictionary will retain it's objects, and copy it's keys.
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]];
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:@""];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With