Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Can I sort the NSDictionary on basis of key?

like image 492
suse Avatar asked Aug 27 '10 09:08

suse


People also ask

What is NSDictionary in Objective c?

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.

How do I sort an array in Objective C?

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.

What is the difference between NSMapTable vs NSDictionary?

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.

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys.


2 Answers

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]]; 
like image 75
Max Seelemann Avatar answered Sep 23 '22 07:09

Max Seelemann


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:@""]; 
like image 37
Vitalii Gozhenko Avatar answered Sep 25 '22 07:09

Vitalii Gozhenko