字母数字数组排序

时间:2013-10-21 07:31:34

标签: ios objective-c nssortdescriptor

我有一个字母数字名称列表,当我运行下面的代码时,数字在A-Z (0-9 A-Z)之前排序。

如何使NSSortDescriptor将数字放在数组(A-Z 0-9)的末尾?

NSSortDescriptor *sortNameSortDescriptor = 
[NSSortDescriptor sortDescriptorWithKey:@"sortName"
ascending:YES
selector:@selector(localizedStandardCompare:)];

NSArray *sortedArray = [sortSectionsArray sortedArrayUsingDescriptors:@[ sortNameSortDescriptor ]];

1 个答案:

答案 0 :(得分:2)

也许您可以使用基于NSComparator的排序描述符?

粗略大纲

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"sortName" ascending:YES
     comparator:^NSComparisonResult(NSString* obj1, NSString* obj2) 
     {
            //Return negative number, zero or positive based on 
            //first letter being number or alpha. 
            //If obj1 starts with a letter and obj2 starts with a number then
            //return NSOrderedAscending. . . otherwise just return [obj1 comppare:obj2];

            //To test if first chararacter is a letter:

            NSRange first = [obj1 rangeOfComposedCharacterSequenceAtIndex:0];
            NSRange match = [obj1 rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet] options:0 range:first];
            if (match.location != NSNotFound) {//Implement above comment}
     }];