SmallChess
SmallChess

Reputation: 8106

Why my NSArray sorter doesn't work?

I have

        if (_sortedThemes == nil)
        {
            _sortedThemes = [[self.themes allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2)
                             {
                                 if ([str1 isEqualToString:@"Default"] && str1 != str2)
                                 {
                                     return NSOrderedAscending;
                                 }
                                 else
                                 {
                                     return [str1 compare:str2];
                                 }
                             }];                        
        }

        for (id d in _sortedThemes)
        {
            NSLog(@"%@",d);
        }

_sortedThemes is indeed nil and the sorter returns:

Blue, ... , Default , ....

I want Default as the first element, everything else in the regular order.

I changed to

if (([str1 isEqualToString:@"Default"] || [str2 isEqualToString:@"Default"]) && str1 != str2)

However, Default is still not the first element.

Upvotes: 0

Views: 75

Answers (2)

prashant
prashant

Reputation: 1920

This sample code might help you

  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 NSOrderedDescending;
}];

Upvotes: 0

Thilo
Thilo

Reputation: 262464

 if ([str1 isEqualToString:@"Default"] && str1 != str2)

"Default" could also be str2. You need to add that case, then it probably works.

Upvotes: 1

Related Questions