Search code examples
objective-cnsarraynsdictionarynssortdescriptor

Sort an NSArray with NSDictionary


I'm using NSSortDiscriptors to sort an NSArray. Every index in the array contains a dictionary with key,value entries. This dictionary also holds another dictionary.

My problem that I want solve is to sort the array based on values on the first dictionary, but also on some values in the dictionary it contains.

The following is the sort method I use for the other values in the array.

- (void)sortArray {

if ([array count] != 0) {

    // Reports sortingDescriptors
    NSSortDescriptor * city = [[NSSortDescriptor alloc] initWithKey:@"City" ascending:YES];
    NSSortDescriptor * name = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES];
    NSSortDescriptor * country = [[NSSortDescriptor alloc] initWithKey:@"Country" ascending:YES];

    [reportsArray sortUsingDescriptors:[NSArray arrayWithObjects:city, name, country, nil]];

    [name release];
    [city release];
    [country release];
}
}

The array looks like this:

[{name = "";
city = "";
country = "";
date = {
 dateAdded = "";
 dateRemoved = "";
}
}];

So I also want to sort on, if have value on dateAdded for example.


Solution

  • You can specify a key path when you create the NSSortDescriptor, this way you can sort the NSArray with a NSDictionary.