简体   繁体   中英

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

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];

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM