2

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]]; 
1
  • What happens if you store your numerical values as NSNumbers instead of NSStrings? Commented Jan 24, 2012 at 22:56

1 Answer 1

3

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.

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

1 Comment

Super. Thanks. Can you explain in detail how it sorted?

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.