Anthony Shahine Anthony Shahine - 2 months ago 13
Swift Question

Save and Read NSArray from NSUserDefaults using Struct

I'm trying to save a string using a struct and NSUserDefaults, and everything goes well.

However I'm not able to do the same for a NSArray,

this is my code,
the Struct :

struct ServiceKey{
static let XX : NSArray = ["xx"]
}


to save :

let defaults = NSUserDefaults.standardUserDefaults()

var first = denominationsALFA as! NSArray
defaults.setObject(first, forKey: ServiceKey.XX)


To read :

let defaults = NSUserDefaults.standardUserDefaults()
defaults.arrayForKey(ServiceKey.XX)


so what could be the best solution for this problem

Answer

Check the syntax of method setObject(:forKey:) here forKey is is type of String parameter, so change you XX type to String from NSArray then use setObject and arrayForKey methods.

struct ServiceKey{
    static let XX: String = "xx"
}

Now Set object in NSUserDefaults

let defaults = NSUserDefaults.standardUserDefaults()
var first = denominationsALFA as! NSArray
defaults.setObject(first, forKey: ServiceKey.XX)

Retrieve object from NSUserDefaults

let defaults = NSUserDefaults.standardUserDefaults()
var array = defaults.arrayForKey(ServiceKey.XX)

For more details check Apple Documentation on NSUserDefaults.