我正在尝试在userDefaults中存储一个数组,但是当我运行我的应用程序时出现此错误:
'尝试插入非属性列表对象( " Morning_Star_2.Event(标题:可选(\"测试标题\"),位置:可选(\"测试位置\"))" )用于关键测试'
这是我的代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var txtTitle: UITextField!
@IBOutlet weak var txtLocation: UITextField!
@IBOutlet weak var txtDate: UITextField!
@IBOutlet weak var txtTime: UITextField!
var eventsArray = [Event]()
@IBAction func btnSave() {
let savedEvents = UserDefaults.standard.object(forKey: "test")
let event = Event(eventTitle: txtTitle.text!, eventLocation: txtLocation.text!)
if let tempEvents = savedEvents {
eventsArray = tempEvents as! [Event]
eventsArray.append(event)
}
else {
let event = Event(eventTitle: txtTitle.text!, eventLocation: txtLocation.text!)
eventsArray.append(event)
}
UserDefaults.standard.set(eventsArray, forKey: "test")
//print(eventsArray)
}
}
答案 0 :(得分:0)
要在UserDefaults中存储自定义对象,您的对象必须
类实现的示例可能如下所示:
class Event: NSObject, NSCoding {
private var eventTitle: String!
private var eventLocation: String!
init(eventTitle: String, eventLocation: String) {
self.eventTitle = eventTitle
self.eventLocation = eventLocation
}
override init() {
}
required convenience init?(coder aDecoder: NSCoder) {
self.init()
eventTitle = aDecoder.decodeObject(forKey: "eventTitle") as? String
eventLocation = aDecoder.decodeObject(forKey: "eventLocation") as? String
}
func encode(with aCoder: NSCoder) {
aCoder.encode(eventTitle, forKey: "eventTitle")
aCoder.encode(eventLocation, forKey: "eventLocation")
}
}
现在,您只能在UserDefaults中存储某些对象。幸运的是,类型数据可以存储在UserDefaults中。然后,您需要将数组转换为Data,然后存储它。
let data = NSKeyedArchiver.archivedData(withRootObject: eventsArray)
// This calls the encode function of your Event class
UserDefaults.standard.set(data, forKey: "test")
/* This saves the object to a buffer, but you will need to call synchronize,
before it is actually saved to UserDefaults */
UserDefaults.standard.synchronize()
当您检索数据时,它会以“任何?”的形式返回,它必须被转换为您的对象:
if let data = UserDefaults.standard.object(forKey: "test") as? Data {
if let storedData = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Event] {
// In here you can access your array
}
}