How to save a specific NSLocale in CoreData

157 views Asked by At

Trying to save Locales into CoreData and just wasn't sure what format I should save the data.

let locale = Locale.current
let currencyCodesArray = Locale.commonISOCurrencyCodes

for currencyCode in currencyCodesArray {

        // let currencyName = locale.displayName(forKey:NSLocale.Key.currencyCode, value : currencyCode)
        let currencyName = locale.localizedString(forCurrencyCode: currencyCode)

        //let currencySymbol = locale.displayName(forKey:NSLocale.Key.currencySymbol, value : currencyCode)
        let currencySymbol = locale.currencySymbol

        let identifier = locale.localizedString(forIdentifier: currencyCode)

         print(identifier);

        if let _ = currencySymbol, let currencyName = currencyName{

            let currencyModel = CurrencyModel()
            currencyModel.currencyName = currencyName
            currencyModel.currencyCode = currencyCode
            currencyModel.currencySymbol = currencySymbol!

            //currencyModel.identifier = identifier

            currencies.append(currencyModel)

            //print(identifier);
        }
    }

From each locale I'm trying to save: currency code - string Identifier - String currency name - String currency symbol - String

Should I be saving each of these properties on their own, or is it possible to save the entire Locale?

2

There are 2 answers

7
vadian On

In Swift it's Locale without NS and without bridge cast

let locale = Locale.current

Save the identifier of the Locale which is a String

let currentIdentifier = Locale.current.identifer

And create a Locale when reading it

let locale = Locale(identifier : currentIdentifier)
1
ezaji On

You can save NSLocale as Transformable attribute.

NSKeyedUnarchiveFromDataTransformerName is used by default to transform your plain object to Core Data storage representation. But in this case your plain object should conform NSCoding or NSSecureCoding protocol.

If you want to transform more complex object you have to subclass NSValueTransformer.

But NSLocale conforms to NSSecureCoding so you can save it directly by setting type of this attribute of your Entity to Transformable.

See the sample from Apple.