How to convert custom array to NSData in swift?

匆匆过客 提交于 2019-12-13 04:09:28

问题


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:


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


来源:https://stackoverflow.com/questions/32528908/how-to-convert-custom-array-to-nsdata-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!