Search code examples
iphoneobjective-ciosnsarraynsdictionary

How can I sort an NSArray containing NSDictionaries?


I have an NSArray which contains NSDictionary objects. Each of these NSDictionary objects contains an ORDER key.

How can I sort this NSArray based on this key within each of these NSDictionaries?


Solution

  • Here is an example. Imagines you have an array of dictionnaries. Ecah dictionnary have 2 keys "name" & "dateOfBirth". You can sort your array by "name" like this :

    //
    // Sort array by name
    //
    NSSortDescriptor *Sorter = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    [myArray sortUsingDescriptors:[NSArray arrayWithObject:Sorter]];
    [Sorter release];
    

    Note that myArray is a NSMutableArray.