如何从货币代码获取NSLocale?

时间:2011-08-02 07:52:21

标签: objective-c currency nslocale

我正在尝试这个:

NSDictionary *components = [NSDictionary dictionaryWithObject:@"USD" forKey:NSLocaleCurrencyCode];
NSString *localeIdentifier = [NSLocale localeIdentifierFromComponents:components];
NSLocale *localeForDefaultCurrency = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];

它创建NSLocale对象但它不包含任何区域信息。例如,

[localeForDefaultCurrency objectForKey:NSLocaleCountryCode];

返回nil;

知道如何从货币代码中获取NSLocale吗?

4 个答案:

答案 0 :(得分:8)

由一些客人在pastebin发布:

NSDictionary *components = [NSDictionary dictionaryWithObject:@"USD" forKey:NSLocaleCurrencyCode];
NSString *localeIdentifier = [NSLocale localeIdentifierFromComponents:components];
NSLocale *localeForDefaultCurrency = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];

[localeForDefaultCurrency objectForKey:NSLocaleCountryCode];

答案 1 :(得分:5)

有一些技巧,比如创建带有id的区域设置,而不是像“en_US”这样的正常区域设置ID传递货币代码“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;
}

答案 2 :(得分:5)

    NSDictionary *localeInfo = @{NSLocaleCurrencyCode: currencyCode, NSLocaleLanguageCode: [[NSLocale preferredLanguages] objectAtIndex:0]};

    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:
                        [NSLocale localeIdentifierFromComponents:localeInfo]];

答案 3 :(得分:1)

您可以在 Swift 中使用扩展程序的强大功能:

extension NSLocale {

    static func currencySymbolFromCode(code: String) -> String? {
       let localeIdentifier = NSLocale.localeIdentifierFromComponents([NSLocaleCurrencyCode : code])
       let locale = NSLocale(localeIdentifier: localeIdentifier)
       return locale.objectForKey(NSLocaleCurrencySymbol) as? String
    }

}

通过这种方式,代码中的任何位置:

let code = "EUR"
let price = 10
if let currencySymbol = NSLocale.currencySymbolFromCode(code) as? String {
    print("You have to pay \(price)\(currencySymbol)")
}