This question already has an answer here:
Sorting array(NSString + Number) using NSSortDescriptor in IOS?
                                
                                    (1个答案)
                                
                        
                                2年前关闭。
            
                    
我有一个包含数字的字符串数组,即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]];

关于ios - Objective-C用正确的字母数字字符串排序NSArray ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43096557/

10-10 04:27