How can I sort an NSMutableArray alphabetically?

41,518

Solution 1

You can do this to sort NSMutableArray:

[yourArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

Solution 2

The other answers provided here mention using @selector(localizedCaseInsensitiveCompare:)
This works great for an array of NSString, however the OP commented that the array contains objects and that sorting should be done according to object.name property.
In this case you should do this:

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
[yourArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];

Your objects will be sorted according to the name property of those objects.

Solution 3

NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; // Describe the Key value using which you want to sort. 
NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor]; // Add the value of the descriptor to array.
sortedArrayWithName = [yourDataArray sortedArrayUsingDescriptors:descriptors]; // Now Sort the Array using descriptor.

Here you will get the sorted array list.

Solution 4

In the simplest scenarios, if you had an array of strings:

NSArray* data = @[@"Grapes", @"Apples", @"Oranges"];

And you wanted to sort it, you'd simply pass in nil for the key of the descriptor, and call the method i mentioned above:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
data = [data sortedArrayUsingDescriptors:@[descriptor]];

The output would look like this:

Apples, Grapes, Oranges

For more details check this

Share:
41,518
Ali
Author by

Ali

Updated on June 09, 2021

Comments

  • Ali
    Ali almost 3 years

    I want to sort an NSMutableArray alphabetically.