简体   繁体   English

基于多个属性对NSArray进行排序

[英]Sort NSArray based on multiple properties

Here's the problem i have :- I have an array 这是我的问题: - 我有一个数组

Item1,
Item2,
Item3,
Item4,
Item5,
Item6,
Item7,
....,Item11

I need to sort this array in that specific order ,ofcourse all the values are of type 'NSString' 我需要按照特定的顺序对这个数组进行排序,当然所有的值都是'NSString'类型

if i use 如果我使用

sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)

it sorts it like this:- 它像这样排序: -

Item1,
Item10,
Item11,
Item2,
Item3,
Item4,
Item5,
Item6,
Item7,
Item8,
Item9

I can manually extract the numeric value from this but i thought there may be a better way to do this perhaps by using 'NSComparator'. 我可以手动从中提取数值,但我认为可能有一种更好的方法可以通过使用'NSComparator'来实现。

Use it like this: 像这样使用它:

NSArray *arry = [[NSArray alloc] initWithObjects:@"Item1",@"Item2",@"Item3",@"Item4",@"Item5",@"Item11",@"Item10",@"Item6", nil];
NSArray *sortedStrings = [arry sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
NSLog(@"sortedStrings---%@",sortedStrings);
NSInteger sortFile(id a, id b, void* context) {
    return [a compare:b options:NSNumericSearch];
}

[yourArray sortedArrayUsingFunction:mySort context:nil];

This code works for me: 这段代码适合我:

NSArray *array = [NSArray arrayWithObjects:@"Item1",
                  @"Item10",
                  @"Item11",
                  @"Item2",
                  @"Item3", nil];

array = [array sortedArrayUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
    return [str1 compare:str2 options:(NSNumericSearch)];
} ];

NSLog(@"%@", array);

Try this: 尝试这个:

 NSArray *sortedStrings = [yourArray sortedArrayUsingSelector:@selector(localizedStandardCompare:)];

For more sortedArrayUsingSelector 对于更多sortedArrayUsingSelector

如果你使用sortedArrayUsingFunction:context,你可以实现你想要的任何功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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