How do I sort Unicode (foreign) strings in my iPhone application?
All strings in Objective-C (NSString*) are unicode strings. They are sequences of unicode characters (as opposed to sequences of encoded bytes). You can sort an array of strings using the methods provided by NSArray.
NSArray* myArray = [NSArray arrayWithObjects:@"はじめまして", @"русский язык", @"คนอ้วน ๆ", nil];
NSArray* mySortedArray = [myArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
This will sort the strings by their unicode order, if you have some other sorting condition then provide a custom sorting selector or elaborate on your question.
If you want to sort using sort descriptors, you can also sort like so:
NSSortDescriptor *sorter = [NSSortDescriptor descriptorWithKey:@"description" ascending:YES];
NSArray* mySortedArray = [myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sorter]];
"description" works OK as a key for NSString values, since description is documented to return itself.
The advantage of going the NSSortDescriptor route is that you can have more than one sort descriptor, or you can select to use a descending sort instead.
Hi all, Thanks for helping me.
localizedCaseInsensitiveCompare
this API will do the sorting with respect to localization. Otherwise strings of different languages will be treated as a unicode strings and comparison fails.
Here is the solution:
NSComparisonResult sortLocationsForStr(NSString* str1, NSString* str2, void *context)
{
return [str1 localizedCaseInsensitiveCompare:str2];
}
[myArrayToSort sortUsingFunction:sortLocationsForStr context:nil];