所以我需要对一个内部有数组的数组进行排序,如下所示:
NSMutableArray * array_example = [[NSMutableArray alloc] init];
[array_example addObject:[NSMutableArray arrayWithObjects:
string_1,
string_2,
string_3,
nil]
];如何通过数组的"string_1“字段对此数组进行排序?你知道我该怎么做吗?
谢谢
发布于 2011-08-22 18:06:55
对于iOS 4和更高版本,使用comparator块很容易做到这一点:
[array_example sortUsingComparator:^(NSArray *o1, NSArray *o2) {
return (NSComparisonResult)[[o1 objectAtIndex:0] compare:[o2 objectAtIndex:0]];
}];如果你对模块的工作原理感兴趣,你可以看看苹果的Short Practical Guide to Blocks。
如果你希望支持iOS 3.x,你必须使用一个自定义的比较函数:
NSComparisonResult compareArrayFirstElement(NSArray *o1, NSArray *o2) {
return [[o1 objectAtIndex:0] compare:[o2 objectAtIndex:0]];
}然后使用:
[array_example sortUsingFunction:compareArrayFirstElement context:nil];发布于 2011-08-22 18:10:29
您可以循环数组对象并在每个子数组上调用sortedArrayUsingSelector,然后替换objects :withObject以注入回原始数组
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);https://stackoverflow.com/questions/7145723
复制相似问题