Search code examples
iosnsarraynsdictionarynssortdescriptoralphabetical-sort

NSSortDescriptor not sorting alphabetically


I've a dictionary which I'd like to sort alphabetically based on the firstName :

{
    id = 123;
    user =     {
        firstName = "Test 15";
        sex = Male;
    };
},
{
    id = 23;
    user =     {
        firstName = "Test 12";
        sex = Male;
    };
}

I tried the following code to sort :

NSSortDescriptor *sorter = [[NSSortDescriptor alloc]
                                         initWithKey:@"user.firstName"
                                         ascending:YES
                                         selector:@selector(localizedCaseInsensitiveCompare:)];

[arrayToBeSorted sortedArrayUsingDescriptors:[NSArray arrayWithObject:sorter]]

But the above code doesn't seem to work.

Any idea on what might have gone wrong?


Solution

  • sortedArrayUsingDescriptors: creates a new array which will be sorted and returns it. You don't store that array anywhere. The original is untouched, and your code throws the sorted array away.

    Method calls tend to be named so that their name indicates what it does. If you want to sort an array (which needs to be mutable, otherwise you can't sort it), there will be methods called something like sortUsing... Something like "sortedArrayUsing..." clearly returns a new array. You have an array, and the method gives you a sorted array.