How can I sort an array filled with [UIFont familyNames]
into alphabetical order?
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.
An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.
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
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:)];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With