How can I sort an array filled with [UIFont familyNames]
into alphabetical order?

- 4,149
- 1
- 23
- 43

- 5,143
- 5
- 30
- 32
7 Answers
The simplest approach is, to provide a sort selector (Apple's documentation for details)
Objective-C
sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
Swift
let descriptor: NSSortDescriptor = NSSortDescriptor(key: "YourKey", ascending: true, selector: "localizedCaseInsensitiveCompare:")
let sortedResults: NSArray = temparray.sortedArrayUsingDescriptors([descriptor])
Apple provides several selectors for alphabetic sorting:
compare:
caseInsensitiveCompare:
localizedCompare:
localizedCaseInsensitiveCompare:
localizedStandardCompare:
Swift
var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
students.sort()
print(students)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"

- 3,365
- 5
- 35
- 52

- 34,177
- 3
- 81
- 112
-
5Documentation link is outdated, code sample isn't really enough to actually sort the array. localizedCaseInsensitiveCompare: needs to be defined somehow. – M. Ryan Dec 20 '10 at 15:40
-
34I updated the link. Thanks for pointing that out. localizedCaseInsensitiveCompare: is a method of NSString and should be sufficient to sort an array of strings. – Thomas Zoechling Dec 20 '10 at 16:37
-
1And this can be easily applied to an array containing any custom objects (not just NSString). You just have to make sure that all objects inside your array have implemented the message that the selector is specifying. Then inside this message you just call the NSString compare for the properties of your object that you want to compare. – lgdev Jun 22 '12 at 18:00
-
Such simple things must not be so complex. – Dmitry Jan 28 '19 at 06:33
The other answers provided here mention using @selector(localizedCaseInsensitiveCompare:)
This works great for an array of NSString, however if you want to extend this to another type of object, and sort those objects according to a 'name' property, you should do this instead:
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
sortedArray=[anArray sortedArrayUsingDescriptors:@[sort]];
Your objects will be sorted according to the name property of those objects.
If you want the sorting to be case insensitive, you would need to set the descriptor like this
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];

- 33,281
- 23
- 160
- 191

- 6,707
- 2
- 21
- 26
-
14+1, Thank you. Funny this is the more common use case than the accepted answer. – Vinay W Nov 23 '12 at 05:27
-
4
-
+1, The sort descriptor along with selector is exactly what I wanted and no other answer had this. Thanks a lot man – Ganesh Somani Oct 15 '13 at 13:58
-
1I get an error when I try to sort an array of strings this way, because `name` is not a valid key. What key do I use to sort strings alphabetically with an NSSortDescriptor? – temporary_user_name Nov 24 '14 at 21:38
A more powerful way of sorting a list of NSString to use things like NSNumericSearch :
NSArray *sortedArrayOfString = [arrayOfString sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
}];
Combined with SortDescriptor, that would give something like :
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
}];
NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];

- 3,965
- 3
- 30
- 34
Another easy method to sort an array of strings consists by using the NSString description
property this way:
NSSortDescriptor *valueDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES];
arrayOfSortedStrings = [arrayOfNotSortedStrings sortedArrayUsingDescriptors:@[valueDescriptor]];
-
1That seems a bit useless; there's no reason to sort strings this way (and there's probably a performance hit for doing so), and for other objects, its description property is rarely useful for sorting purposes. – mah Feb 18 '18 at 22:31
Use below code for sorting in alphabetical order:
NSArray *unsortedStrings = @[@"Verdana", @"MS San Serif", @"Times New Roman",@"Chalkduster",@"Impact"];
NSArray *sortedStrings =
[unsortedStrings sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"Unsorted Array : %@",unsortedStrings);
NSLog(@"Sorted Array : %@",sortedStrings);
Below is console log :
2015-04-02 16:17:50.614 ToDoList[2133:100512] Unsorted Array : (
Verdana,
"MS San Serif",
"Times New Roman",
Chalkduster,
Impact
)
2015-04-02 16:17:50.615 ToDoList[2133:100512] Sorted Array : (
Chalkduster,
Impact,
"MS San Serif",
"Times New Roman",
Verdana
)

- 35,723
- 18
- 170
- 177
This already has good answers for most purposes, but I'll add mine which is more specific.
In English, normally when we alphabetise, we ignore the word "the" at the beginning of a phrase. So "The United States" would be ordered under "U" and not "T".
This does that for you.
It would probably be best to put these in categories.
// Sort an array of NSStrings alphabetically, ignoring the word "the" at the beginning of a string.
-(NSArray*) sortArrayAlphabeticallyIgnoringThes:(NSArray*) unsortedArray {
NSArray * sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSString* a, NSString* b) {
//find the strings that will actually be compared for alphabetical ordering
NSString* firstStringToCompare = [self stringByRemovingPrecedingThe:a];
NSString* secondStringToCompare = [self stringByRemovingPrecedingThe:b];
return [firstStringToCompare compare:secondStringToCompare];
}];
return sortedArray;
}
// Remove "the"s, also removes preceding white spaces that are left as a result. Assumes no preceding whitespaces to start with. nb: Trailing white spaces will be deleted too.
-(NSString*) stringByRemovingPrecedingThe:(NSString*) originalString {
NSString* result;
if ([[originalString substringToIndex:3].lowercaseString isEqualToString:@"the"]) {
result = [[originalString substringFromIndex:3] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
else {
result = originalString;
}
return result;
}

- 830
- 8
- 21
-
1I just looked at this years later, and I realised it should also include "a" and "an". These should be easy to add. – narco Nov 06 '19 at 23:09
-(IBAction)SegmentbtnCLK:(id)sender
{ [self sortArryofDictionary];
[self.objtable reloadData];}
-(void)sortArryofDictionary
{ NSSortDescriptor *sorter;
switch (sortcontrol.selectedSegmentIndex)
{case 0:
sorter=[[NSSortDescriptor alloc]initWithKey:@"Name" ascending:YES];
break;
case 1:
sorter=[[NSSortDescriptor alloc]initWithKey:@"Age" ascending:YES];
default:
break; }
NSArray *sortdiscriptor=[[NSArray alloc]initWithObjects:sorter, nil];
[arr sortUsingDescriptors:sortdiscriptor];
}

- 11
- 1