作为一个面向协议编程的概念,我使用Struct创建了我的模型。
我想把"Struct"的数组保存到Userdefault中。但是,在对该模型的数组进行编码/解码时,我遇到了问题。
这是我的模型结构:
当我尝试像这样保存arrRoomList(一组房间对象的数组)时:
我想把"Struct"的数组保存到Userdefault中。但是,在对该模型的数组进行编码/解码时,我遇到了问题。
这是我的模型结构:
struct Room {
let name : String
let id : String
let booked : Bool
}
我创建了一个像这样的扩展
extension Room {
func decode() -> Room? {
let userClassObject = NSKeyedUnarchiver.unarchiveObject(withFile: RoomClass.path()) as? RoomClass
return userClassObject?.room
}
func encode() {
let personClassObject = RoomClass(room: self)
NSKeyedArchiver.archiveRootObject(personClassObject, toFile: RoomClass.path())
}
class RoomClass: NSObject, NSCoding {
var room : Room?
init(room: Room) {
self.room = room
super.init()
}
class func path() -> String {
let documentsPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
let path = documentsPath?.appending(("/Room"))
return path!
}
func encode(with aCoder: NSCoder) {
aCoder.encode(room!.name, forKey: "name")
aCoder.encode(room!.id, forKey: "Id")
aCoder.encode(room!.booked, forKey: "booked")
}
required init?(coder aDecoder: NSCoder) {
let _name = aDecoder.decodeObject(forKey: "name") as? String
let _id = aDecoder.decodeObject(forKey: "Id") as? String
let _booked = aDecoder.decodeBool(forKey: "booked")
room = Room(name: _name!, id: _id!, booked: _booked)
super.init()
}
}
}
当我尝试像这样保存arrRoomList(一组房间对象的数组)时:
self.saveRooms(arrayRooms: arrRoomList)
我遇到了这个错误
[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance
我也尝试过先对每个对象进行编码,然后再尝试将它们保存在默认设置中,但仍然出现错误。
请问有人可以指导我如何正确地对用户默认设置中的结构体数组进行编码/解码,而不必将其转换为字典吗?