开发者

Problem sorting NSMutableArray

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(@"开发者_StackOverflowallObjects: %@", 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?


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.


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 )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜