Allison
Allison

Reputation: 2383

Sort NSMutableArray with strings that contain numbers?

I have a NSMutableArray and it has the users high scores saved into it. I want to arrange the items numerically (the numbers are stored in NSStrings.)
Example:
4,2,7,8
To
2,4,7,8
What is the simplest way to do this if the data is stored in NSStrings?

Upvotes: 7

Views: 6398

Answers (5)

Benpaper
Benpaper

Reputation: 144

The answer from Darshit Shah make it smootly

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc]initWithKey:@"rank"  ascending:YES selector:@selector(localizedStandardCompare:)];

Upvotes: 0

MD SHAHIDUL ISLAM
MD SHAHIDUL ISLAM

Reputation: 14523

If the array is of nsdictionaries conaining numeric value for key number

isKeyAscending = isKeyAscending ? NO : YES;

[yourArray sortUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {

    NSString *str1 = [obj1 objectForKey:@"number"];
    NSString *str2 = [obj2 objectForKey:@"number"];

    if(isKeyAscending) { //ascending order
        return [str1 compare:str2 options:(NSNumericSearch)];
    } else { //descending order
        return [str2 compare:str1 options:(NSNumericSearch)];
    }
}];

//yourArray is now sorted

Upvotes: 1

Adam
Adam

Reputation: 26917

This code will do it:

//creating mutable array
NSMutableArray *myArray = [NSMutableArray arrayWithObjects:@"4", @"2", @"7", @"8", nil];

//sorting
[myArray sortUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
    return [str1 compare:str2 options:(NSNumericSearch)];
}];

//logging
NSLog(@"%@", myArray);

It uses blocks, make sure your target OS supports that (It's 4.0 for iOS and 10.6 for OSX).

Upvotes: 23

Jeff Hellman
Jeff Hellman

Reputation: 2117

The NSMutableArray method sortUsingSelector: should do it:

[scoreArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]

should do it.

Upvotes: 1

pasawaya
pasawaya

Reputation: 11595

This code works. I tried it:

NSMutableArray *unsortedHighScores = [[NSMutableArray alloc] initWithObjects:@"4", @"2", @"7", @"8", nil];

NSMutableArray *intermediaryArray = [[NSMutableArray alloc] init];

for(NSString *score in unsortedHighScores){
    
    NSNumber *scoreInt = [NSNumber numberWithInteger:[score integerValue]];
    [intermediaryArray addObject:scoreInt];
}

NSArray *sortedHighScores = [intermediaryArray sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@", sortedHighScores);

The output is this:

2

4

7

8

If you have any questions about the code, just ask in the comments. Hope this helps!

Upvotes: 2

Related Questions