在iPhone SDK中使用货币代码显示货币符号

时间:2011-06-08 13:03:57

标签: iphone cocoa currency symbols nslocale

实际上,我想显示所有货币代码的货币符号,我正在使用这样的代码,但我只得到“$”符号

-(void) showCurrenciesList
{
    NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];                         
    [numFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    //[numFormatter setLocale: [NSLocale currentLocale]];

    NSMutableArray *aryAllCurrencies = [[NSMutableArray alloc] init]; 
    //NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier: @"en_US"] autorelease];

    NSArray *currencyArray = [NSLocale ISOCurrencyCodes]; 
    NSLog(@"Currency array : %@",currencyArray);

    for (NSString *currencyCode in currencyArray) 
    {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        [numFormatter setCurrencyCode:currencyCode];
        NSString *currencySymbol = [numFormatter currencySymbol];
        [aryAllCurrencies addObject:currencySymbol];
        [pool release];     
    }   
    //[countriesArray sortUsingSelector:@selector(compare:)];
    NSLog(@"currencies array : %@",aryAllCurrencies);   
}

这是对的,还是有另一种方法可以做到这一点?

2 个答案:

答案 0 :(得分:4)

这是一个直接的高成本解决方案

+(NSString *)getCurrencySybolByCurrecyCode:(NSString *)code
{
    NSArray *locales = [NSLocale availableLocaleIdentifiers];
    for (NSString *currentLocale in locales)
    {
        NSLocale *currentLoc = [[[NSLocale alloc] initWithLocaleIdentifier:currentLocale] autorelease];
        if([[currentLoc objectForKey:NSLocaleCurrencyCode] isEqualToString:code])
        {
            NSLog(@"find symbol for code = %@ %@", [currentLoc objectForKey:NSLocaleCurrencyCode], [currentLoc objectForKey:NSLocaleCurrencySymbol]);
            return [currentLoc objectForKey:NSLocaleCurrencySymbol];        }
    }
    return nil;
}

答案 1 :(得分:3)

来自可可手册:Typically, therefore, you should use drain instead of release。实际上你根本不需要NSAutoreleasePool。但这不是你问题的原因。问题在于语言环境。 NSNumberFormatter具有已分配的区域设置。如果您确实想使用NSNumberFormatter,则应在发送currencySymbol消息之前更改您的语言环境。 但我建议你像在第一段代码中那样使用NSLocale

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier: @"en_US"];
NSString *dollar = [locale displayNameForKey:NSLocaleCurrencyCode value:@"USD"];
[locale release];

在发布之前,我已经检查了两次此代码。