简体   繁体   中英

Sorting using NSSortDescriptor

I'm having a problem regarding sorting.

Data is like this

NSArray* testArr = @[@{@"key":@"aaa", @"value":@"asdfaf"},
                     @{@"key":@"baa", @"value":@"bsdfaf"},
                     @{@"key":@"!!aaa", @"value":@"adsfdfaf"},
                     @{@"key":@"123aaa", @"value":@"cecdfaf"},
                     @{@"key":@"@@#21", @"value":@"a42faf"},
                     @{@"key":@"ace", @"value":@"a123faf"},
                     @{@"key":@"321!!", @"value":@"123sdfaf"},
                     ];

And NSSortDescriptor is like this

NSLocale *locale = [NSLocale autoupdatingCurrentLocale];        
NSSortDescriptor *sortUsingNameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"key" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {

    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSWidthInsensitiveSearch | NSForcedOrderingSearch | NSNumericSearch;
    NSRange stringRange = NSMakeRange(0, ((NSString *)obj1).length);

    return [(NSString*)obj1 compare:(NSString*) obj2 options:comparisonOptions range:stringRange locale:locale];
    }];

this is the result.

{
    key = "!!aaa";
    value = adsfdfaf;
},
    {
    key = "@@#21";
    value = a42faf;
},
    {
    key = 123aaa;
    value = cecdfaf;
},
    {
    key = "321!!";
    value = 123sdfaf;
},
    {
    key = aaa;
    value = asdfaf;
},
    {
    key = ace;
    value = a123faf;
},
    {
    key = baa;
    value = bsdfaf;
}

But I want to sort it like this

{
    key = aaa;
    value = asdfaf;
},
    {
    key = ace;
    value = a123faf;
},
    {
    key = baa;
    value = bsdfaf;
},
{
    key = 123aaa;
    value = cecdfaf;
},
{
    key = "321!!";
    value = 123sdfaf;
},
{
    key = "!!aaa";
    value = adsfdfaf;
},
{
    key = "@@#21";
    value = a42faf;
}

It is alphabet, number and special char sequence. How can i do that

    NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:@selector(localizedCompare:)];
NSArray* sortedArray = [inFileTypes sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

I afraid you will have to create your own comparator. Please look at this answer Easy way to put blank strings at end of sort using NSSortDescriptor?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM