views:

302

answers:

3

Hello experts!

I have an array named 'names' with strings looking like this: ["name_23_something", "name_25_something", "name_2_something"]; Now I would like to sort this array in ascending order so it looks like this: ["name_25_something", "name_23_something", "name_2_something"];

I guess that should start of with extracting the numbers since I want that the sorting is done by them:

for(NSString *name in arr) {
    NSArray *nameSegments = [name componentsSeparatedByString:@"_"];
    NSLog("number: %@", (NSString*)[nameSegments objectAtIndex:1]);     
}

I'm thinking of creating a dictionary with the keys but I'm not sure if that is the correct objective-c way, maybe there some some methods I could use instead? Could you please me with some tips or example code how this sorting should be done in a proper way.

Thank you

+2  A: 

Check out -[NSArray sortedArrayUsingComparator:].

Graham Lee
Unfortunately not available on the iPhone OS.
Ed Marty
@ed: no, but a little inhibative use of the scroll bar takes us from that entry in the documentation to the plethora of other ‘-sortedArrayUsing…‘ methods.
Graham Lee
+2  A: 
@implementation NSString (MySort)

- (int) myValue {
    NSArray *nameSegments = [self componentsSeparatedByString:@"_"];
    return [[nameSegments objectAtIndex:1] intValue];
}

- (NSComparisonResult) myCompare:(NSString *)other {
    int result = [self myValue] - [other myValue];
    return result < 0 ? NSOrderedAscending : result > 0 ? NSOrderedDescending : NSOrderedSame;
}

@end

...

arr = [arr sortedArrayUsingSelector:@selector(myCompare:)];
Ed Marty
A: 

Hello! Thank you for your answers!

I did like this, what do you think:

NSInteger sortNames(id v1, id v2, void *context) {
    NSArray *nameSegments = [(NSString*)v1 componentsSeparatedByString:@"_"];
    NSArray *nameSegments2 = [(NSString*)v2 componentsSeparatedByString:@"_"];
    int num1 = [[nameSegments objectAtIndex:1] integerValue];
    int num2 = [[nameSegments2 objectAtIndex:1] integerValue];
    if (num1 < num2)
        return NSOrderedDescending;
    else if (num1 > num2)
        return NSOrderedAscending;

    return NSOrderedSame;
}

names = [names sortedArrayUsingFunction:sortNames context:nil];

This will result in:

["name_25_something", "name_23_something", "name_2_something"];
jakob