You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS应用保加利亚字符д大小写不敏感搜索异常求助

解决保加利亚字符大小写不敏感搜索/排序异常问题

问题原因

localizedCaseInsensitiveCompare: 方法依赖当前系统或应用的默认区域设置,若未明确指定保加利亚语区域,系统可能无法正确识别保加利亚字符(如‘д’/‘Д’)的大小写等价关系,导致比较失效。

解决方案

1. 修改排序方法,指定保加利亚语区域

替换原有的排序描述符初始化逻辑,使用带明确区域设置的比较器Block,确保保加利亚字符按本地规则处理:

- (NSMutableArray *)sortMethod:(NSArray *)array SortingKey:(NSString *)key Ascending:(BOOL)ascending CaseInsensitiveCompare:(BOOL)caseInCompare
{
    if(key && key.length > 0)
    {
        NSSortDescriptor *sortDescriptor = nil;
        if(caseInCompare)
        {
            // 初始化保加利亚语区域设置
            NSLocale *bulgarianLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"bg_BG"];
            sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:key ascending:ascending comparator:^NSComparisonResult(id obj1, id obj2) {
                NSString *str1 = [obj1 valueForKey:key];
                NSString *str2 = [obj2 valueForKey:key];
                // 使用带区域的大小写不敏感比较
                return [str1 caseInsensitiveCompare:str2 withOptions:0 range:NSMakeRange(0, str1.length) locale:bulgarianLocale];
            }];
        }
        else
        {
            sortDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:ascending];
        }
        NSArray *sortedArray = [array sortedArrayUsingDescriptors:@[sortDescriptor]];
        return [NSMutableArray arrayWithArray:sortedArray];
    }
    
    return nil;
}

2. 同步修正搜索逻辑(若搜索单独实现)

如果搜索功能未和排序共用比较逻辑,需确保搜索时也使用保加利亚语区域进行大小写不敏感匹配:

// 示例:过滤包含搜索文本的数组
NSString *searchInput = @"д"; // 用户输入的小写字符
NSLocale *bgLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"bg_BG"];
NSArray *filteredResults = [yourDataSourceArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id item, NSDictionary *bindings) {
    NSString *targetString = [item valueForKey:@"yourSearchKey"];
    // 用指定区域的大小写不敏感匹配
    NSRange matchRange = [targetString rangeOfString:searchInput options:NSCaseInsensitiveSearch locale:bgLocale];
    return matchRange.location != NSNotFound;
}]];

注意事项

  • 确保项目已添加保加利亚语本地化支持:在项目设置的 Localizations 列表中添加 Bulgarian (bg),保证系统能加载对应的字符处理规则。
  • 若需支持多语言,可根据用户当前语言动态获取区域([NSLocale currentLocale]),但面向保加利亚用户场景下,硬编码bg_BG能避免系统区域切换带来的异常。

内容的提问来源于stack exchange,提问作者SonalB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 16:46:13