jakob
jakob

Reputation: 5995

Sorting array containing strings in objective c

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

Upvotes: 1

Views: 5784

Answers (3)

jakob
jakob

Reputation: 5995

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

Upvotes: 1

Ed Marty
Ed Marty

Reputation: 39690

@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:)];

Upvotes: 2

user23743
user23743

Reputation:

Check out -[NSArray sortedArrayUsingComparator:].

Upvotes: 2

Related Questions