0

I am trying to save data by NSUserDefaults . Here is my code

 @IBAction func saveBtn(sender: AnyObject) {
    var userName = nameLbl.text
    UserInfo.append(User(name: userName))
    NSUserDefaults.standardUserDefaults().setObject(UserInfo, forKey: "UserInfo")
    userName = ""

}

But when i click on save button, it is showing Attempt to set a non-property-list object . I think, UserInfo array need to convert as NSData . Please tell me how can i do that?

1
  • 1
    Read up on NSKeyedArchiver as one solution. Commented Sep 11, 2015 at 17:24

1 Answer 1

0

You need to make your custom object conform to the NSCoding protocol, and implement the encode and decode methods. Once you do, you can use the encode method to create an NSData object to use with NSUserDefaults.

Something like this, in your UserInfo class:

required convenience init?(coder decoder: NSCoder) {
    self.init()

    guard let title = decoder.decodeObjectForKey("title") as? String
    else {return nil }

    self.title = title
}

func encodeWithCoder(coder: NSCoder) {
    coder.encodeObject(self.title, forKey: "title")
}

Then, you can use the encoded data with NSUserDefaults like this:

@IBAction func saveBtn(sender: AnyObject) {
    var userName = nameLbl.text
    UserInfo.append(User(name: userName))
    let data = NSKeyedArchiver.archivedDataWithRootObject(UserInfo)
    NSUserDefaults.standardUserDefaults().setObject(data, forKey: "UserInfo")
    userName = ""
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.