开发者

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:[NSM开发者_Python百科utableArray 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜