使用自定义顺序按字母顺序排序数组

时间:2014-08-04 12:11:38

标签: ios arrays sorting

我正在尝试对音乐应用中的数组进行排序:ABCDEFG ...АБВГ...#547368%; 这是排序:

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

但结果是:ABCDEFG(英文字母).. 1235#45(数字)..АБВГ(俄文字母) 将俄语字母变成字母似乎有问题。

1 个答案:

答案 0 :(得分:2)

问题是当你从字符串中获取字符时:

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

由于char(8位)的最大值为127,因此当您尝试为char分配更大的值时,会出现未定义的行为(俄语字母用16位编码)。

您只需将char替换为unichar即可解决您的问题。