Display currency symbols using currency codes in iPhone SDK

て烟熏妆下的殇ゞ 提交于 2019-12-22 00:52:50

问题


Actually, I want to display the currency symbols of all currency codes and I'm using code like this,but i only get "$" symbols

-(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);   
}

Is this right or is there another way to do this?


回答1:


From cocoa manual: Typically, therefore, you should use drain instead of release. Actually you do not need a NSAutoreleasePool here at all. But it is not a reason of your problem. The problem is in locale. NSNumberFormatter has an assigned locale. If you do want to use NSNumberFormatter you should change your locale before sending currencySymbol message. But I advice you to use NSLocale as you did in your first code:

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

I've checked this code twice before posting.




回答2:


It's a straight high cost solution

+(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;
}


来源:https://stackoverflow.com/questions/6279124/display-currency-symbols-using-currency-codes-in-iphone-sdk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!