How to sort an array which contains Dictionaries?

Ankit Vyas picture Ankit Vyas · Jan 28, 2011 · Viewed 18.4k times · Source

I have an array which contains dictionaries in it; so how can I sort the array according to dictionary key values?

Answer

user557219 picture user557219 · Jan 28, 2011

If every element in the array is a dictionary containing a certain key, you can sort the array using a sort descriptor. For instance, if every element is a dictionary containing a key called "name":

NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:@"name"
    ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors];