(Swift) Storing and retrieving Array to NSUserDefaults

From your code I see you are storing some array

// Your code
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA")

and retrieving a string

//Your code
let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA")

There is probably a type mismatch, You store one type and retrieve another type.

While retrieving either use arrayForKey() or objectForKey() see the code below.

let tabledata = NSUserDefaults.standardUserDefaults().arrayForKey("\(identity.text!)listA") 

or

let tabledata = NSUserDefaults.standardUserDefaults().objectForKey("\(identity.text!)listA")

If it is an array I would go with First one.


Here are the way that you can store and retrieved array of object with help of NSKeyArchive.

To Store array to NSUserDefault.

let placesData = NSKeyedArchiver.archivedData(withRootObject: placesArray)
UserDefaults.standard.set(placesData, forKey: "places")

To Retrieved array from NSUserDefault.

let placesData = UserDefaults.standard.object(forKey: "places") as? NSData

if let placesData = placesData {
    let placesArray = NSKeyedUnarchiver.unarchiveObject(with: placesData as Data) as? [Place]
    print(placesArray)
}

Hope this help you.