0

I have this weird issue. I'm saving custom class object in NSUserDefaults, and while retrieving the data I get nil for int variable of the object. Below is the custom class

class User {
    var name: String?
    var user_id: Int?
    var account_id: Int?
    var location: String?
}

I'm saving the object as,

let defaults = NSUserDefaults.standardUserDefaults()
var data = NSKeyedArchiver.archivedDataWithRootObject([user]) // I can see the int values for the user objects here
defaults.setObject(data, forKey: "all_users")

Retrieving the data as,

let defaults = NSUserDefaults.standardUserDefaults()

let data = defaults.dataForKey("all_users")
var users = [Users]()
if data != nil {
    let userData = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! [Users]

    for usr in userData {
        print("\(usr.name!)") // Prints the name
        print("\(usr.user_id!)") // Nil value here
        users.append(usr)
    }
}

I have absolutely no idea about the reason for this behavior.

Srujan Simha
  • 3,637
  • 8
  • 42
  • 59

1 Answers1

2

Custom classes that have none property list items need to conform to NSCoding to be able to be saved in NSUserDefaults.

Here is a guide to conforming to NSCoding: http://nshipster.com/nscoding/

You will need both of these functions:

init(coder decoder: NSCoder) {
    self.name = decoder.decodeObjectForKey("name") as String
    self.user_id = decoder.decodeIntegerForKey("user_id")
    self.account_id = decoder.decodeIntegerForKey("account_id")
    self.location = decoder.decodeObjectForKey("self.location") as String

}

func encodeWithCoder(coder: NSCoder) {
    coder.encodeObject(self.name, forKey: "name")
    coder.encodeInt(self.user_id, forKey: "user_id")
    coder.encodeInt(account_id, forKey: "account_id")
    coder.encodeObject(self.location, forKey: "location")

}
Wyetro
  • 8,439
  • 9
  • 46
  • 64