Search code examples
objective-csortingnsmutablearraynsdictionarynssortdescriptor

How can I sort an NSMutableArray containing NSDictionary's by numeric values?


Essentially I have an NSMutableArray which contains several NSDictionaries. I wish to sort this array based on one of the numeric values that appears in each of the NSDictionaries.

For example, if these were all of the NSDictionaries:

dict_1
{
    some_val,         @"blah"
    some_other_val,   135
}

dict_2
{
    some_val,         @"blah"
    some_other_val,   10
}

dict_3
{
    some_val,         @"blah"
    some_other_val,   35
}

Then I want to sort them based on the value of "some_other_val". I have attempted to do this using sort descriptors, however I presents me with the wrong results. Here is the code I use to sort the array:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"some_other_val" ascending:NO];
        [myArray sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];

As I mentioned, this does not provide the result I was expecting to see. Here are the results of the sort:

Before:
135
10
35

After:
35
135
10

As far as I can tell it's just trying to sort the values as if they are strings. I have had a look around online to see if I can find a solution to the problem however I'm at a bit of a dead end.

Please could someone offer some advice?


Solution

  • I think that are several forms to do that, the first option:

    I think that if you add some_other_val to the dictionary as NSNumber, you can get the result that you want, without change the rest.

    I'll be looking for others.