views:

31

answers:

1

Hi Folks,

I'm stuck with sorting 2D arrays in objective c. I have a 2D array which I made from two string arrays.

NSArray *totalRatings = [NSArray arrayWithObjects:namesArray,ratingsArray,nil];

I've pulled the values using:

for (int i=0; i<2; i++) {
  for (int j=0; j<5; j++) {
     NSString *strings = [[totalRatings objectAtIndex:i] objectAtIndex:j];
     NSLog(@"i=%i, j=%i, = %@ \n",i,j,strings);
  }
}

Firstly, I wonder whether there is a more elegant method for working with the length of the totalRatings array. Secondly, here is what the totalRatings array contains:

Person 1, 12
Person 2, 5
Person 3, 9
Person 4, 10
Person 7, 2

Since these are all strings, how can these be sorted? I'm looking for:

Person 1, 12
Person 4, 10
Person 3, 9
Person 2, 5
Person 7, 2

I'd appreciate any help you can provide.

A: 

Hey @mac_newbie,

You may want to use a dictionary to deal with this data, instead of two distinct arrays.

Instead of what you have now, why don't you put the record for each person on a dictionary:

NSArray *totalRatings = [NSArray arrayWithObjects:
                             [NSDictionary dictionaryWithObjectsAndKeys:@"Person 1", @"name", [NSNumber numberWithInt:12], @"rating", nil],
                             [NSDictionary dictionaryWithObjectsAndKeys:@"Person 2", @"name", [NSNumber numberWithInt:5], @"rating", nil],
                             [NSDictionary dictionaryWithObjectsAndKeys:@"Person 3", @"name", [NSNumber numberWithInt:9], @"rating", nil],
                             [NSDictionary dictionaryWithObjectsAndKeys:@"Person 4", @"name", [NSNumber numberWithInt:10], @"rating", nil],
                             [NSDictionary dictionaryWithObjectsAndKeys:@"Person 7", @"name", [NSNumber numberWithInt:2], @"rating", nil],
                             nil];
    NSArray *sortedArray = [totalRatings sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"rating" ascending:NO]]];
vfn