mikezs
mikezs

Reputation: 422

sort array alphabeticaly using custom order

I'm trying to sort array like in music app: ABCDEFG...АБВГ...#547368%; here is the sort:

 NSString *sortOrder = @"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzАаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЭэЮюЯя_0123456789";
    NSComparator comp = ^NSComparisonResult(id obj1, id obj2)
    {
        char char1 = [(NSString *)obj1 characterAtIndex: 0];
        char char2 = [(NSString *)obj2 characterAtIndex: 0];

        int index1;
        for (index1 = 0; index1 < sortOrder.length; index1++)
            if ([sortOrder characterAtIndex: index1] == char1)
                break;

        int index2;
        for (index2 = 0; index2 < sortOrder.length; index2++)
            if ([sortOrder characterAtIndex: index2] == char2)
                break;

        if (index1 < index2)
            return NSOrderedAscending;
        else if (index1 > index2)
            return NSOrderedDescending;
        else
            return [(NSString *)obj1 compare: obj2 options: NSCaseInsensitiveSearch];
    };
     NSSortDescriptor *sortDescriptor=[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES comparator:comp];
    arrayOfContactsAndCompanies = (NSMutableArray*)[arrayOfContactsAndCompanies sortedArrayUsingDescriptors:@[sortDescriptor]];

but the result is : ABCDEFG(english letters)..1235#45(digits)..АБВГ(Russian letters) It seems like there is a problem with getting russian letters into char.

Upvotes: 1

Views: 88

Answers (1)

Ayu
Ayu

Reputation: 954

The problem is when you get the characters from your string here:

    char char1 = [(NSString *)obj1 characterAtIndex: 0];
    char char2 = [(NSString *)obj2 characterAtIndex: 0];

Since the maximum value of char (8 bits) is 127, you get undefined behavior when you try to assign a bigger value to that char (The Russian letters are encoded with 16 bits).

You just need to replace char with unichar and it should solve your problem.

Upvotes: 2

Related Questions