Objective-c 按正确的顺序对带有字母数字字符串的 NSArray 进行排序



我有一个包含数字的字符串数组,即 Shift 1 RT9909 我对数组进行排序如下:

NSSet *forms = dataObject.rtForms;
NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"type" ascending:YES];
NSArray *sorted = [forms sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameDescriptor]];

当元素数低于 10 时,这工作正常。在此之后,Shift 10 RT9909被放置在前面 Shift 2 RT9909 .

所以我的问题是我如何对数组进行排序,以便Shift 10 RT9909遵循Shift 9 RT9909

正如 Larme 建议的那样,您需要将ComparatorNSNumericSearch 一起使用,您也可以与NSSortDescriptor结合使用

NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"type" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
    return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
}];
NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameDescriptor]];

相关内容

最新更新