How to do a natural sort on an NSArray? How to do a natural sort on an NSArray? objective-c objective-c

How to do a natural sort on an NSArray?


NSStrings can be compared using the NSNumericSearch compare option.

One version:

NSInteger sort(Obj* a, Obj* b, void*) {    return [[a title] compare:[b title] options:NSNumericSearch];}result = [array sortedArrayUsingFunction:&sort context:nil];

Or a bit more generic:

NSInteger sort(id a, id b, void* p) {    return [[a valueForKey:(NSString*)p]             compare:[b valueForKey:(NSString*)p]            options:NSNumericSearch];}result = [array sortedArrayUsingFunction:&sort context:@"title"]

Or using blocks:

result = [array sortedArrayUsingComparator:^(Obj* a, Obj* b) {     return [[a title] compare:[b title] options:NSNumericSearch]; }];


Those attempting to replicate the Finder's sorting behavior on Mac OS X 10.6 and later and iOS 4 and later can use localizedStandardCompare: as the comparator selector.

Those with the same goal on earlier versions of Mac OS X and/or iOS should use the solution described in the String Programming Guide.


Based on @PeterHosey's answer, if you're working with an array of string objects:

SHORT ANSWER:

NSArray *orderedTitles = [unorderedTitles sortedArrayUsingSelector:@selector(localizedStandardCompare:)];

FULL EXAMPLE:

NSArray *unorderedTitles = @[    @"file12",    @"file1",    @"file10",    @"file3",    @"file2",    @"file11"];NSArray *orderedTitles = [unorderedTitles sortedArrayUsingSelector:@selector(localizedStandardCompare:)];NSLog(@"orderedTitles = %@", orderedTitles);/*orderedTitles = (    file1,    file2,    file3,    file10,    file11,    file12)*/