iOS: Custom object's int variable returns nil in NSUserDefaults

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.

Answers


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")

}

Need Your Help

Flash Builder / Eclipse is not starting

eclipse apache-flex flash-builder

It is stuck on the Splash Screen (or the dock icon has the 3 or 4 vertical lines). It doesn't go past that and no error message.

how to add Copy Pods Resources back?

xcode cocoapods

I accidentally deleted "Copy Pods Resources", how can I add it back?