1


I am aware that there is a lot of questions about this topic, and i do apologize for that as i just cant get this to work for my NSMutableArray. I have problem to really understand the sorting and i have been reading documentation

I have an NSMutableArray with the following type of data:

Player name
score
Player name
score
Player name
score
...

It is a combination between a name and a score (NSNumber). I am trying to find a way to sort this based on the score. I have read a lot but i just do not get this to work, i also have problem to understand the sort concept. I have tried to sort the full array but...

I would very much appreciate if someone can give me a short, understandable, explanation of the sort scenario for this and also an example of how to sort this.

Edit: I changed to dictionary, selected the values and was thinking to sort the allObjects (stored as NSNumber in the dict) and then just select the key from the dict based on the sorted object.

NSArray *allPlayers = [playerResultInTheGame allKeys];
NSArray *allObjects = [playerResultInTheGame allValues];

NSLog(@"allPlayers: %@", allPlayers);
NSLog(@"allObjects: %@", allObjects);

NSMutableArray *sortedArray = [allObjects   sortedArrayUsingSelector:@selector(Compare:)];

I get the following when i run this:

2011-01-16 21:10:08.417 XX[6640:207] playerResultInTheGame: {
Barnspelare = 3;
Vuxenspelare = 3;
}
2011-01-16 21:10:08.418 XX[6640:207] allPlayers: (
Barnspelare,
Vuxenspelare
)
2011-01-16 21:10:08.418 XX[6640:207] allObjects: (
3,
3
)
2011-01-16 21:10:08.419 XX[6640:207] -[NSCFNumber Compare:]: unrecognized selector sent to instance 0x5b26f10
2011-01-16 21:10:08.422 XX[6640:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFNumber Compare:]: unrecognized selector sent to instance 0x5b26f10'

Can someone please advice as i do not really understand this?

1
  • 1
    Why an array and not a dictionary? Commented Jan 16, 2011 at 18:31

2 Answers 2

2

What you need to do here is to store your scores and player names in a dictionary. Use the player name as the key (unless the same player is included more than once) and the score as the value. Then, sorting the players is as easy as this:

NSDictionary *dict; // initialize dictionary with key/value pairs
NSArray *allPlayers = [dict allKeys];

Sort the allPlayers array however you want, then get the scores out of the dictionary.

Sign up to request clarification or add additional context in comments.

3 Comments

As stated in the question, the OP wants to sort on score, so it would make sense to use the score as the keys and the player names as the values, I suspect.
Not necessarily. You can still sort by value, but you cannot have multiple keys with the same value (same score, different people).
I do not have multiple keys. I still just dont get the sort to work, anyone that can help me to show how the sort will look like?
0
Lets go. 

1) You need to create array of dictionaries. 2) Then sort it. 3) Then create final array of strings and numbers from sorted array of dictionaries.    

    //for example you have this

    NSArray *allPlayers = @[@"John",@"Carl",@"Elena",@"Anna"];
    NSArray *allAges    = @[@30,    @25,    @16,     @21];

    //created storage to sort results
   NSMutableArray *sortedPlayers = [NSMutableArray new];

    [allPlayers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        //I do not know if you have same count of player names and ages allways
        //so just to prevent app crash check this situation
        if (allAges.count <= idx){
            *stop = YES;
            return ;
        }

        [sortedPlayers addObject:@{
                           @"name":obj,
                           @"age":allAges[idx]
                           }];
    }];

    //let the sort begin
    [sortedPlayers sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        NSNumber *age1 = obj1[@"age"];
        NSNumber *age2 = obj2[@"age"];

        //just leave comparing to the NSNumber object
        return  [age1 compare:age2];
    }];

    NSLog(@"Wow. It works!\n:%@",sortedPlayers);

    //now you need the initial array with player\age values
    NSMutableArray *result = [NSMutableArray new];

    //append each pair to result
     for (NSDictionary *obj in sortedPlayers){

        NSString *name = obj[@"name"];
        NSNumber *age = obj[@"age"];

        [result addObject:name];
        [result addObject:age];
    }

    NSLog(@"The final result is\n:%@",result);

This will produce the following result in console:

( Elena, 16, Anna, 21, Carl, 25, John, 30 )

2 Comments

Thanks but it is a bit late :-)
@PeterK I thought about this but maybe for someone it would be useful )

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.