1

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

3 Answers 3

2
@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:)];
Sign up to request clarification or add additional context in comments.

Comments

2

Check out -[NSArray sortedArrayUsingComparator:].

2 Comments

Unfortunately not available on the iPhone OS.
@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.
1

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"];

1 Comment

That looks good, apart from the name of the function. compareNames would be better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.