Search code examples
iosswiftstructnsarraynsuserdefaults

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


Solution

  • 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.