像使用NSSortDescriptor的NSInteger一样对NSString值进行排序

Abh*_*nav 28 iphone cocoa-touch objective-c nssortdescriptor ios

我创建了一个排序描述符来排序来自我的服务器的plist响应.这适用于值为9的排序键.超过10个项目我看到突然结果,排序键按顺序排列= 1,10,11,2,3,4,5,6,7,8,9

NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sort" ascending:YES];
self.myList = [NSMutableArray arrayWithArray:[unsortedList sortedArrayUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]];
Run Code Online (Sandbox Code Playgroud)

如何按正确的顺序排列1,2,3,4,5,6,7,8,9,10,11?

jon*_*oll 44

您可以通过在创建时实现自定义比较器块来执行此操作NSSortDescriptor:

NSSortDescriptor *aSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"sort" ascending:YES comparator:^(id obj1, id obj2) {

    if ([obj1 integerValue] > [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }
    if ([obj1 integerValue] < [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];
self.myList = [NSMutableArray arrayWithArray:[unsortedList sortedArrayUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]];
Run Code Online (Sandbox Code Playgroud)

见苹果文档在这里

  • 请注意,此解决方案不适用于 CoreData fetchRequests,因为它不接受基于块的描述符。 (2认同)

Vin*_*ble 39

[list sortUsingSelector:@selector(localizedStandardCompare:)];将以"人类"的方式对列表进行排序(因此"11"将持续到最后,而不是"1"和"2"之间).但如果你真的想将这些字符串视为数字,那么你应该先将它们作为数字!


小智 16

NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sort.intValue" ascending:YES];
self.myList = [NSMutableArray arrayWithArray:[unsortedList sortedArrayUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]];
Run Code Online (Sandbox Code Playgroud)

根据整数的值排序.


Jos*_*ell 11

您需要将您的字符串与NSNumericSearch选项进行比较:

NSNumericSearch
的字符串中的数字是使用比较了数值,也就是Name2.txt< Name7.txt< Name25.txt.

这需要compare:options:调用方法进行比较.

为此,您的排序描述符可以使用NSComparator:

[NSSortDescriptor sortDescriptorWithKey:@"self"
                              ascending:YES
                             comparator:^(NSString * string1, NSString * string2){
                                            return [string1 compare:string2
                                                            options:NSNumericSearch];
 }];
Run Code Online (Sandbox Code Playgroud)

或者,实际上,您可以跳过排序描述符并使用相同的块直接对数组进行排序:

[unsortedList sortedArrayUsingComparator:^NSComparisonResult (NSString * string1, NSString * string2){
    return [string1 compare:string2
                    options:NSNumericSearch];
 }];
Run Code Online (Sandbox Code Playgroud)


Flu*_*imp 7

NSMutableArray *list = [NSMutableArray arrayWithObjects:@"11",@"2",@"3",@"1", nil];
[list sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSInteger firstInteger = [obj1 integerValue];
    NSInteger secondInteger = [obj2 integerValue];
    if( firstInteger > secondInteger) return NSOrderedDescending;
    if( firstInteger == secondInteger) return NSOrderedSame;
    return NSOrderedAscending; // edited
}];
Run Code Online (Sandbox Code Playgroud)

不保证性能