Jeremy
Jeremy

Reputation: 883

Trying to sort multidimensional mutable array with one (integer) object

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.

Upvotes: 0

Views: 466

Answers (1)

Anomie
Anomie

Reputation: 94834

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.

Upvotes: 4

Related Questions