Sorting using NSSortDescriptor

257 views Asked by At

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

2

There are 2 answers

0
agy On BEST ANSWER

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?

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