Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a NSArray alphabetically?

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

like image 444
DotSlashSlash Avatar asked Aug 29 '09 11:08

DotSlashSlash


People also ask

How do you sort an array of objects in Objective C?

The trick to sorting an array is a method on the array itself called "sortedArrayUsingDescriptors:". The method takes an array of NSSortDescriptor objects. These descriptors allow you to describe how your data should be sorted.

What is Nsarray?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.


2 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"]" 

Reference

like image 94
Thomas Zoechling Avatar answered Sep 28 '22 08:09

Thomas Zoechling


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:)]; 
like image 25
JP Hribovsek Avatar answered Sep 28 '22 08:09

JP Hribovsek