DaSilva
DaSilva

Reputation: 1358

How to order NSMutableArray with NSMutableArray inside

I need so sort an array with an array inside, something like this:

 NSMutableArray * array_example = [[NSMutableArray alloc] init];

 [array_example addObject:[NSMutableArray arrayWithObjects:
                            string_1,
                            string_2,
                            string_3,
                            nil]
 ];

how can i order this array by the field "string_1" of the array??? any idea how can i do that?

Thanks

Upvotes: 0

Views: 371

Answers (2)

Jilouc
Jilouc

Reputation: 12714

For iOS 4 and later, this is easily done using a comparator block:

[array_example sortUsingComparator:^(NSArray *o1, NSArray *o2) {
    return (NSComparisonResult)[[o1 objectAtIndex:0] compare:[o2 objectAtIndex:0]];
}];

If you're interested in how blocks work, you can have a look at Apple's Short Practical Guide to Blocks.

If you wish to support iOS 3.x, you'd have to use a custom comparison function:

NSComparisonResult compareArrayFirstElement(NSArray *o1, NSArray *o2) {
    return [[o1 objectAtIndex:0] compare:[o2 objectAtIndex:0]];
}

and then use:

[array_example sortUsingFunction:compareArrayFirstElement context:nil];

Upvotes: 1

Daniel
Daniel

Reputation: 23359

You can loop the array objects and call sortedArrayUsingSelector on each sub array, then replaceObjectAtIndex:withObject to inject back into the original array

    NSMutableArray * array_example = [[NSMutableArray alloc] init];

    [array_example addObject:[NSMutableArray arrayWithObjects:
                            @"z",
                            @"a",
                            @"ddd",
                            nil]
    ];
    [array_example addObject:[NSMutableArray arrayWithObjects:
                            @"g",
                            @"a",
                            @"p",
                            nil]
    ];
    NSLog(@"Original Array: %@", array_example);

    for(int i = 0; i < [array_example  count] ; i++){
        [array_example replaceObjectAtIndex:i withObject:[[array_example objectAtIndex:i] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]];
        // order sub array
    }
    NSLog(@"Sorted Array: %@", array_example);

Upvotes: 1

Related Questions