Can I get the code for the local currency from an NSLocale?
Asked Answered
A

2

9

Can I get the code for the local currency from an NSLocale? I tried this:

NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"] autorelease];
NSString *currencyCode = [locale objectForKey:NSLocaleCurrencyCode];

but currencyCode comes back as nil (I wanted "EUR", or similar).

Anastigmatic answered 14/11, 2011 at 18:6 Comment(1)
This work for me. This is not a memory problem?Chromatin
R
20

Your code works perfectly fine for me in a regular Macintosh app.

NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"] autorelease];
NSString *currencyCode = [locale objectForKey:NSLocaleCurrencyCode];
NSLog( @"currencyCode is %@", currencyCode );

displays this in the console:

2011-11-14 14:53:33.784 Testing[26388:707] currencyCode is EUR

Are you trying to build this as a command line (Foundation) app or something non-traditional-Mac-like?

Regionalism answered 14/11, 2011 at 19:55 Comment(5)
iPhone, rather than Mac. Could that be it?Anastigmatic
Same code works on my iPhone, Simon. Try dropping those lines of code into a brand new iPhone app (like I just did), just for testing, and you should see that they do work for you. I think something else is going on with your iPhone app. You should remove the "osx" tag from this question, b.t.w. :-)Regionalism
BTW, the locale is autoreleased, so isn't that a double release in your last line?Anastigmatic
Ah - found my mistake; I was actually passing @"fr" not @"fr_FR" to initWithLocaleIdentifier:. Serves me right for not posting my full code.Anastigmatic
in my case i had to get it dynamically so used NSLocale *locale = [NSLocale currentLocale]; rest is all the same.. Thanks +1Diluvium
Y
0

NSLocale has a method called - objectForKey: that returns an object corresponding to a specified NSLocale component key passed as a parameter. With Swift 2.2, - objectForKey: has the following declaration:

func objectForKey(_ key: AnyObject) -> AnyObject?

Among the many NSLocale component keys, Apple states about NSLocaleCurrencyCode:

The key for the currency code associated with the locale. The corresponding value is an NSString object; for example, "USD".


Therefore, you can retrieve the currency code linked to a NSLocale instance with the following Swift 2.2 and Swift 3 code snippets:

Swift 2.2

import Foundation

let locale = NSLocale(localeIdentifier: "fr_FR")
//let locale = NSLocale.currentLocale()
let localeCurrencyCode = locale.objectForKey(NSLocaleCurrencyCode) as! String
print(localeCurrencyCode) // prints "EUR"

Swift 3

import Foundation

let locale = Locale(localeIdentifier: "fr_FR")
//let locale = Locale.current
let localeCurrencyCode = locale.object(forKey: Locale.Key.currencyCode) as! String
print(localeCurrencyCode) // prints "EUR"
Yellowthroat answered 13/7, 2016 at 15:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.