Wednesday, April 25, 2012

Sort String Array

The following code demonstrates how to sort an array of strings in Objective-C:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    @autoreleasepool {
        
        NSArray *stringsArray = [NSArray arrayWithObjects:
                                 @"string 1",
                                 @"String 21",
                                 @"string 12",
                                 @"String 11",
                                 @"String 02", nil];
        static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch |
        NSWidthInsensitiveSearch | NSForcedOrderingSearch;
        NSLocale *currentLocale = [NSLocale currentLocale];
        NSComparator finderSort = ^(id string1, id string2) {
            NSRange string1Range = NSMakeRange(0, [string1 length]);
            return [string1 compare:string2 options:comparisonOptions range:string1Range locale:currentLocale];
        };
        
        NSArray* sortedArray = [stringsArray sortedArrayUsingComparator:finderSort];
        NSLog(@"finderSort: %@", sortedArray);        
    }
    return 0;
}
This code is taken from iOS Developer Library.

No comments:

Post a Comment