如何快速将自定义数组转换为 NSData? [英] How to convert custom array to NSData in swift?
问题描述
我正在尝试通过 NSUserDefaults
保存数据.这是我的代码
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 = ""
}
但是当我点击保存按钮时,它显示 Attempt to set a non-property-list object
.我认为, UserInfo
数组需要转换为 NSData
.请告诉我我该怎么做?
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?
推荐答案
您需要使您的自定义对象符合 NSCoding
协议,并实现编码和解码方法.完成后,您可以使用 encode 方法创建一个 NSData 对象以与 NSUserDefaults 一起使用.
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.
像这样,在你的 UserInfo 类中:
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")
}
然后,您可以像这样使用带有 NSUserDefaults 的编码数据:
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 = ""
}
这篇关于如何快速将自定义数组转换为 NSData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!