0

I have an multidimensional NSMutableArray and I want to sort it on one of the objects. The array is created so:

        [NSMutableArrayName addObjectsFromArray:[NSMutableArray arrayWithObjects:[NSMutableArray arrayWithObjects:name,[NSNumber numberWithInteger:x],nil],nil]];       

I can't find a way to sort the entire array using the value of the second object (the integer x).

Help appreciated as always.

1 Answer 1

4

This sounds like a good case for sortUsingComparator:. You use it something like this:

[NSMutableArrayName sortUsingComparator:^NSComparisonResult(id o1, id o2){
    NSInteger a = [[o1 objectAtIndex:1] integerValue]; // Or however to extract the int from your array element
    NSInteger b = [[o2 objectAtIndex:1] integerValue];

    if (a < b) return NSOrderedAscending;
    if (a > b) return NSOrderedDescending;
    return NSOrderedSame;
}];

If you're targeting pre-iOS 4.0, you can accomplish much the same thing using sortUsingFunction:context: and putting the block content into a C-style function.

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

1 Comment

Wow. That is really impressive and works great. Thanks Anomie

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.