Alec
Alec

Reputation: 483

Sort an NSMutableArray of nested NSArrays by value atIndex

I have an NSMutableArray that contains many NSArrays. At a specific (static) index in each NSArray is a value that I would like to sort my NSMutableArray by (descending/greatest to least). Right now I'm trying to use NSSortDescriptor, but can't figure how to grab and compare the value at my specific index via KVC. To elaborate:

#define INDEX_OF_DESIRED_STRING 2

NSArray *a1 = [NSArray arrayWithObjects:@"test", @"jjj", @"3454", nil]; 
NSArray *a2 = [NSArray arrayWithObjects:@"test1", @"jjj", @"12", nil]; 
NSArray *a3 = [NSArray arrayWithObjects:@"test2", @"jjj", @"232333", nil]; 
NSArray *a4 = [NSArray arrayWithObjects:@"test3", @"jjj", @".122", nil]; 

NSMutableArray *mutableA = [[NSMutableArray alloc] initWithObjects:a1, a2, a3, a4, nil]; 

// Then I'd sort with something like this... although this of course
// does not take the arrays into account. Sorts as if it were only made of strings

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"floatValue"
                                                 ascending:NO];

[mutableA sortUsingDescriptors:[NSArray arrayWithObject:sd]]; 

Upvotes: 2

Views: 635

Answers (1)

Andrew Madsen
Andrew Madsen

Reputation: 21383

Try sorting using a comparator block:

NSArray *a1 = [NSArray arrayWithObjects:@"test", @"jjj", @"3454", nil]; 
NSArray *a2 = [NSArray arrayWithObjects:@"test1", @"jjj", @"12", nil]; 
NSArray *a3 = [NSArray arrayWithObjects:@"test2", @"jjj", @"232333", nil]; 
NSArray *a4 = [NSArray arrayWithObjects:@"test3", @"jjj", @".122", nil]; 

NSMutableArray *mutableA = [[NSMutableArray alloc] initWithObjects:a1, a2, a3, a4, nil];

NSLog(@"mutableA before sorting: %@", mutableA);

[mutableA sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSArray *array1 = (NSArray *)obj1;
    NSArray *array2 = (NSArray *)obj2;
    NSString *num1String = [array1 objectAtIndex:INDEX_OF_DESIRED_STRING];
    NSString *num2String = [array2 objectAtIndex:INDEX_OF_DESIRED_STRING];

    return [num1String compare:num2String];
}];

NSLog(@"mutableA after sorting: %@", mutableA);

The comparator block is more verbose than it could be, but I wanted it to be clear what was going on.

Upvotes: 3

Related Questions