gpt4 book ai didi

ios - 将自定义词典保存为用户默认值

转载 作者:可可西里 更新时间:2023-11-01 01:25:08 26 4
gpt4 key购买 nike

struct AllItemsData {
var DSTBID: String!
var CCAS: String!
var BCAS: String!
}

这是我创建类型数组的结构AllItemsDataArray = [AllItemsData()]

添加一些数据后,现在我想将其存储到用户默认值中。

我是这样做的:

AllItemsDataArray.removeFirst()

let archivedArray = NSKeyedArchiver.archivedData(withRootObject: All_ItemsDataArray)
print(archivedArray)
preference.set(archivedArray, forKey: allItemsDataKey)

但是错误是这样的:

ios[1540:537869] -[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x15d1e200

崩溃发生前数组中的值是:

AllItemsData(DSTBID: GGGGGGGGGGGG, CCAS: , BCAS: )
AllItemsData(DSTBID: HHHHHHHHHHHH, CCAS: , BCAS: )

最佳答案

您需要为您的对象实现 NSCoding 协议(protocol),并使用 class 而不是 struct

class AllItemsData: NSObject, NSCoding {
var DSTBID: String!
var CCAS: String!
var BCAS: String!

required convenience init?(coder decoder: NSCoder) {
let DSTBID = decoder.decodeObjectForKey("DSTBID") as? String,
let CCAS = decoder.decodeObjectForKey("CCAS") as? String,
let BCAS = decoder.decodeObjectForKey("BCAS") as? [String]

self.init(
DSTBID: DSTBID,
CCAS: CCAS,
BCAS: BCAS
)
}

func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.DSTBID, forKey: "DSTBID")
coder.encodeObject(self.CCAS, forKey: "CCAS")
coder.encodeInt(Int32(self.BCAS), forKey: "BCAS")
}
}

关于ios - 将自定义词典保存为用户默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41962673/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com