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:]:无法识别的选择器已发送到实例0x15d1e200

崩溃发生之前的数组中的值为:

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

最佳答案

您需要为对象实现NSCoding协议,并使用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/

10-12 03:36