Search code examples
objective-cnsmutablearraynsmutabledictionary

How to sort an array which contains Dictionaries?


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


Solution

  • 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];