FLX FLX - 1 year ago 79
Swift Question

store array of custom class with nested custom class to standardUserDefaults

Swift 2
Xcoode 7.3

I try to store this:

var someArray = [Class1(id: 1, titel: "Titel 2", something: Class2(somevar: 20))]

with NSUSerDefaults:

let arrayData = NSKeyedArchiver.archivedDataWithRootObject(someArray)
NSUserDefaults.standardUserDefaults().setObject(arrayData, forKey: "array")

My classes look like this:

class Class1 {

var id: Int
var titel: String!
var something: Class2

init(id: Int, titel: String, something: Class2) {
self.id = id
self.titel = titel
self.something = something


required init(coder aDecoder: NSCoder) {
self.id = aDecoder.decodeIntForKey("id")
self.titel = aDecoder.decodeStringForKey("titel")

func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(id, forKey: "id")
aCoder.encodeObject(titel, forKey: "titel")

class Class2: Class1

var somevar: Int

init(setback: Int) {
self.somevar = somevar


What do I need to add in those classes?

(Have to add some mor details; but I think it's self-explaining)

Answer Source

it's very easy.


self.something = aDecoder.decodeObjectForKey("something") as! Class2


aCoder.encodeObject(something, forKey: "something")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download