views:

915

answers:

2

I have an NSArray containing numbers as NSString objects. ie.

[array addObject:[NSString stringWithFormat:@"%d", 100]];

How do I sort the array numerically? Can I use compare:options and specify NSNumericSearch as NSStringCompareOptions? Please give me an example/sample code.

+3  A: 

Since your objects are numbers, instead of using NSString objects, you could use NSNumber objects (easily turned into strings via the stringValue property) and sort the array using sortedArrayUsingDescriptors:.

For example:

NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil];
[sorter release];
NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:sorters];
[sorters release];
gerry3
+5  A: 

You can use the example code given for the sortedArrayUsingFunction:context: method which should work fine for NSStrings too as they also have the intValue method.

// Place this functions somewhere above @implementation
static NSInteger intSort(id num1, id num2, void *context)
{
    int v1 = [num1 intValue];
    int v2 = [num2 intValue];
    if (v1 < v2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}

// And used like this
NSArray *sortedArray; 
sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];
epatel
+1 You can replace the body of intSort with just this line: return [(NSString*)num1 compare:num2 options:NSNumericSearch];
gerry3
@gerry3 Sure, I just pulled the example code given at apple.com which looked like it would do the job
epatel