[英]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??? 我如何通过数组的字段“ string_1”订购此数组? any idea how can i do that? 知道我该怎么做吗?
Thanks 谢谢
For iOS 4 and later, this is easily done using a comparator block: 对于iOS 4及更高版本,可以使用比较器块轻松完成此操作:
[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 . 如果您对块的工作方式感兴趣,可以查看Apple的《块实用简短指南》 。
If you wish to support iOS 3.x, you'd have to use a custom comparison function: 如果您希望支持iOS 3.x,则必须使用自定义比较功能:
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 您可以循环数组对象并在每个子数组上调用sortedArrayUsingSelector,然后替换ObjectAtIndex: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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.