NSLocale setPreferredLanguage

Nee*_*esh 2 iphone objective-c nsuserdefaults nssortdescriptor nslocale

我似乎围绕这个问题进行了讨论,现在我不会去.

我试图强制我的应用程序的语言(瑞典语),如下所示.

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

我已经在main方法中完成了它,因此只要应用程序启动就会设置首选项.

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

NSSortDescriptor*valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"iName"升序:YES选择器:@selector(localizedCaseInsensitiveCompare :)];

NSArray*descriptors = [NSArray arrayWithObject:valueDescriptor];

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

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

我究竟做错了什么?

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

Rob*_*ier 6

@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;
}
Run Code Online (Sandbox Code Playgroud)