gpt4 book ai didi

iphone - NSLocale 设置首选语言

转载 作者:行者123 更新时间:2023-12-03 20:28:10 25 4
gpt4 key购买 nike

我似乎一直在围绕这个问题兜圈子,但现在却无路可走。

我正在尝试强制我的应用程序的语言(瑞典语),如下所示。

@autoreleasepool {
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"sv", nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults]synchronize];
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}

我已在主方法中完成此操作,以便应用程序启动后立即设置首选项。

然后,当我想按字母顺序对数组进行排序时,我使用 NSSortDescriptor 和选择器 localizedCaseInsensitiveCompare:

NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"iName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];

NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor];

self.ingredientsList = [NSMutableArray arrayWithArray:[self.ingredientsList sortedArrayUsingDescriptors:descriptors]];

但我的问题是第一次不会用我的本地语言进行排序。但如果我重新启动应用程序,则会根据语言(瑞典语)进行排序。为什么第一次不会发生?

我做错了什么?

帮助/建议将不胜感激。谢谢

最佳答案

@DarkDust 是正确的。您不应该尝试修改区域设置本身。这不在你的控制之下,正如你所看到的,它的效果不是很好。最重要的是,如果您只想修改一个排序操作,那么这是一个非常大的锤子......您可以使用各种本地化 Info.plist 条目(特别是 CFBundleLocalizations)使其正常工作,但不仅仅是对单个列表进行排序。

您要使用的是 compare:options:range:locale:,它允许您传递特定的区域设置。您可以在 sortedArrayUsingSelector:sortedArrayUsingComparator: 内部使用此方法。

或者,您可以使用类别将自定义 swedishCaseInsensitiveCompare: 添加到 NSString。然后,您可以像当前一样使用 NSSortDescriptor

<小时/>

示例。在英语中,ä 排在 a 之后,但在瑞典语中,排在 z 之后:

@interface NSString (SwedishSorting)
- (NSComparisonResult)caseInsensitiveSwedishCompare:(id)other;
@end

@implementation NSString (SwedishSorting)
- (NSComparisonResult)caseInsensitiveSwedishCompare:(id)other;
{
return [self compare:other options:NSCaseInsensitiveSearch range:NSMakeRange(0, self.length) locale:[[NSLocale alloc] initWithLocaleIdentifier:@"sv"]];
}

@end

int main(int argc, const char * argv[])
{

@autoreleasepool {
NSArray *array = [@"Jag är en test av sortering" componentsSeparatedByString:@" "];
NSArray *englishSort = [array sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(caseInsensitiveCompare:)]]];
NSLog(@"English = %@", englishSort);

NSArray *swedishSort = [array sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(caseInsensitiveSwedishCompare:)]]];

NSLog(@"Swedish = %@", swedishSort);
}
return 0;
}

关于iphone - NSLocale 设置首选语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9352116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com