Sorting NSString values as if NSInteger using NSSortDescriptor

前端 未结 7 1498
执念已碎
执念已碎 2020-11-28 09:10

I have created a sort descriptor to sort a plist response coming from my server. This works well with sort key having values upto 9. With more than 10 items I see abrupt res

相关标签:
7条回答
  • 2020-11-28 10:09

    You need your strings to be compared with the NSNumericSearch option:

    NSNumericSearch
    Numbers within strings are compared using numeric value, that is, Name2.txt < Name7.txt < Name25.txt.

    which requires the compare:options: method to be called for the comparison.

    In order to do that, your sort descriptor can use an NSComparator Block:

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

    Or, indeed, you can skip the sort descriptor and simply sort the array directly, using the same Block:

    [unsortedList sortedArrayUsingComparator:^NSComparisonResult (NSString * string1, NSString * string2){
        return [string1 compare:string2
                        options:NSNumericSearch];
     }];
    
    0 讨论(0)
提交回复
热议问题