Mohamed Elkassas
Mohamed Elkassas

Reputation: 869

Sort NSArray of NSString alphabetical Arabic first

How to sort an NSArray containing strings alphabetically but I want the arabic strings to have priority than english and to be put on top of the sorted array

Upvotes: 1

Views: 533

Answers (2)

Mohamed Elkassas
Mohamed Elkassas

Reputation: 869

I have done it the same way :)

    -(NSArray*)arabicFirstSortedArray:(NSArray*)arr {    

    static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch |
    NSWidthInsensitiveSearch | NSForcedOrderingSearch;

    NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"ar"];

    NSArray *sortedArray = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        NSRange string1Range = NSMakeRange(0, [obj1 length]);

        return [obj1 compare:obj2 options:comparisonOptions range:string1Range locale:locale];
    }];

    return sortedArray;
}

This is another way to make arabic string be on top but leave the sorting as it is

-(NSArray*)arabicFirstSortedArray:(NSArray*)arr {
NSArray *sortedArray = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

    BOOL isFirstArabic = [self isArabicString:obj1];
    BOOL isSecondArabic = [self isArabicString:obj2];

    if (isFirstArabic == isSecondArabic) {
        return NSOrderedSame;
    }
    else if(isFirstArabic){
        return NSOrderedAscending;
    }
    else{
        return NSOrderedDescending;
    }
}];

return sortedArray;
}

-(BOOL)isArabicString:(NSString*)str {

NSString *isoLangCode = (__bridge_transfer NSString*)CFStringTokenizerCopyBestStringLanguage((__bridge CFStringRef)str, CFRangeMake(0, str.length));

if([isoLangCode isEqualToString:@"ar"]){
    return YES;
}
else{
    return NO;
}
}

Upvotes: 1

SGDev
SGDev

Reputation: 2252

You can make it work by using compare:options:range:locale: and specifying Arabic locale explicitly, like this:

NSArray *strings=[NSArray arrayWithObjects:@"as", @"ol", @"st", nil]; // also contain 
NSLocale *locale=[[NSLocale alloc] initWithLocaleIdentifier:@"ar_BH"];

NSArray *sorted=[strings sortedArrayUsingComparator:^(NSString *first, NSString *second) {
    return [second compare:first
                  options:0
                    range:NSMakeRange(0, [second length])
                   locale:locale];
}];

for (NSString *s in sorted) { NSLog(@"%@", s); }

Upvotes: 0

Related Questions