kas*_*tet 7 currency objective-c nslocale
我在尝试这个:
NSDictionary *components = [NSDictionary dictionaryWithObject:@"USD" forKey:NSLocaleCurrencyCode];
NSString *localeIdentifier = [NSLocale localeIdentifierFromComponents:components];
NSLocale *localeForDefaultCurrency = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
Run Code Online (Sandbox Code Playgroud)
它创建NSLocale对象,但它不包含任何区域信息.例如,
[localeForDefaultCurrency objectForKey:NSLocaleCountryCode];
Run Code Online (Sandbox Code Playgroud)
返回零;
知道如何从货币代码中获取NSLocale吗?
小智 8
由一些客人在pastebin发布:
NSDictionary *components = [NSDictionary dictionaryWithObject:@"USD" forKey:NSLocaleCurrencyCode];
NSString *localeIdentifier = [NSLocale localeIdentifierFromComponents:components];
NSLocale *localeForDefaultCurrency = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
[localeForDefaultCurrency objectForKey:NSLocaleCountryCode];
Run Code Online (Sandbox Code Playgroud)
有一些技巧,如创建具有id的区域设置,而不是正常的区域设置ID,如"en_US"传递货币代码"USD","EUR"等,它似乎适用于eur和usd我可以检查它但这个是的错误方式恕我直言.
我知道的唯一正确方法是获取所有区域设置,然后循环检查其货币代码以与您拥有的货币代码进行比较.这样,当您找到代码时,您将停止循环.
- (NSLocale *) findLocaleByCurrencyCode:(NSString *)_currencyCode
{
NSArray *locales = [NSLocale availableLocaleIdentifiers];
NSLocale *locale = nil;
NSString *localeId;
for (localeId in locales) {
locale = [[[NSLocale alloc] initWithLocaleIdentifier:localeId] autorelease];
NSString *code = [locale objectForKey:NSLocaleCurrencyCode];
if ([code isEqualToString:_currencyCode])
break;
else
locale = nil;
}
/* For some codes that locale cannot be found, init it different way. */
if (locale == nil) {
NSDictionary *components = [NSDictionary dictionaryWithObject:_currencyCode
forKey:NSLocaleCurrencyCode];
localeId = [NSLocale localeIdentifierFromComponents:components];
locale = [[NSLocale alloc] initWithLocaleIdentifier:localeId];
}
return locale;
}
Run Code Online (Sandbox Code Playgroud)
NSDictionary *localeInfo = @{NSLocaleCurrencyCode: currencyCode, NSLocaleLanguageCode: [[NSLocale preferredLanguages] objectAtIndex:0]};
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:
[NSLocale localeIdentifierFromComponents:localeInfo]];
Run Code Online (Sandbox Code Playgroud)