简体   繁体   中英

How to convert custom array to NSData in swift?

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?

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 = ""
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM