排序 NSMutableArray 删除第一个元素

Sorting NSMutableArray Removing First Element

当 NSMutableArray 包含如下对象时,如何对其进行数字排序:

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"P3",@"P1",@"P4",@"P10", nil];

同样的输出应该是这样的:P1、P3、P4、P10

假设字符串的开头总是有一个字符,那么:

[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSInteger i1 = [[obj1 substringFromIndex:1] integerValue];
    NSInteger i2 = [[obj2 substringFromIndex:1] integerValue];
    if (i1 > i2)
        return NSOrderedDescending;
    else if (i1 < i2)
        return NSOrderedAscending;
    return NSOrderedSame;
}];

您需要使用NSNumericSearch

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

来自 Header 文档-

NSNumericSearch = 64, /* Added in 10.2; Numbers within strings are compared using numeric value, that is, Foo2.txt < Foo7.txt < Foo25.txt; only applies to compare methods, not find */

希望这就是您要找的。

您还可以使用 NSSortDescriptorNSArrayNSMutableArray 进行排序。

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES];
NSArray *sortedArray = [<arrayToBeSorted> sortedArrayUsingDescriptors:@[sd]];
NSLog(@"Result = %@", sortedArray);

试试这个代码:

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"P3",@"P1",@"P4",@"P10", nil];

NSLog(@"Array: %@",array);
NSSortDescriptor *lastNameDescriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES selector:@selector(localizedStandardCompare:)];

NSArray *sorters = [[NSArray alloc] initWithObjects:lastNameDescriptor, nil];

NSArray *sortedArray = [array sortedArrayUsingDescriptors:sorters];

NSMutableArray *sortArray = [[NSMutableArray alloc] init];

[sortArray addObjectsFromArray:sortedArray];

NSLog(@"sortArray : %@",sortArray);

输出::

2016-06-15 16:47:47.707 test[5283:150858] Array: (
P3,
P1,
P4,
P10
)
2016-06-15 16:47:47.708 test[5283:150858] sortArray : (
P1,
P3,
P4,
P10
)