views:

141

answers:

1

I have two arrays used in a small game.

If the player gets a score above a certain value their name & score gets output via an UILabel.

NSArray *namesArray = [mainArray objectForKey:@"names"];
NSArray *highScoresArray = [mainArray objectForKey:@"scores"];

I need the UILabels to display with the highest score in descending order, with the corresponding name. I've used an NSSortDescriptor to sort the score values numerically.

NSSortDescriptor *sortDescriptor; sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO] autorelease];

    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    NSArray *sortedScore = [[NSArray alloc]init];
    sortedScore = [scoresArray sortedArrayUsingDescriptors:sortDescriptors];

        NSMutableArray *scoreLabels = [NSMutableArray arrayWithCapacity:10];

    [scoreLabels addObject:scoreLabel1];
    ......

            NSUInteger _index = 0;
    for (NSNumber *_number in sortedScore) {
        UILabel *_label = [scoreLabels objectAtIndex:_index];
        _label.text = [NSString stringWithFormat:@"%d", [_number intValue]];
        _index++;
    }

This works well enough as the scores now display in descending order.

The problem is that I need the corresponding name to also display according in the new sorted order.

I cant use the same sort selector and I don't wont to sort them alphabetically, they need

to correspond to the name/score values that were first input.

Thanks in advance

+1  A: 

You need to put the name and the score together into a single instance of NSDictionary, and then have an NSArray of those NSDictionary instances. Then when you sort by score, you can pull up the corresponding name.

lucius
Thanks lucius. Something like this ...NSDictionary *entry1 = [[NSDictionary alloc]initWithObjectsAndKeys:@"Dave",@"name",@"103",@"score",nil]; NSArray *array = [[NSArray alloc]initWithObjects:entry1,nil];
Yup, that looks about right.
lucius