无法使用NSKeyedArchiver保存我的模型

问题描述 投票:1回答:1

我正在从Api获取模型,它看起来像这样:

class Device : NSObject, Codable, NSCoding{
    var deviceId : Int?
    var driver : String?
    var address : String?
    var type : DeviceTypes? // Enum type

    func encode(with coder: NSCoder) {
        coder.encode(self.deviceId, forKey: "deviceId")
        coder.encode(self.driver, forKey: "driver")
        coder.encode(self.address, forKey: "address")
        coder.encode(self.type, forKey: CodingKeys.type.rawValue)
    }
    required init?(coder: NSCoder) {
        super.init()

        self.deviceId = coder.decodeInteger(forKey: "deviceId")
        self.driver = coder.decodeObject(forKey: "driver") as? String
        self.address = coder.decodeObject(forKey: "address") as? String
        self.type = coder.decodeObject(forKey: CodingKeys.type.rawValue) as? DeviceTypes
    }

    private enum CodingKeys : String, CodingKey{
        case deviceId, address, type, deviceType
    }
}

然后我在数组中添加了一些元素,并且可以正常工作,但是当我尝试使用NSKeyedArchiver对其进行存档时,它会抛出异常:

[____ SwiftValue encodeWithCoder:]:无法识别的选择器已发送到实例

DeviceTypes

enum DeviceTypes : Int, Codable{
    case SYSTEM
    case CE
    case CZ
    case ST
    case KA
    case CR
    case EX
    case DR
    case KL
    case WE
    case WY
    case WL
    case TR
    case LI
    case BR = 30
    case DC = 32
}
ios swift enums nscoding nskeyedarchiver
1个回答
0
投票

您的问题是NSCoding仅适用于类类型。任何试图使DeviceTypes符合NSCoding都会导致错误

enum DeviceTypes : Int, Codable, NSCoding {

非类类型'DeviceTypes'不符合类协议'NSCoding'

一种解决方案是在enum方法中从NSCoding类型来回转换。

请注意,NSCoding已软弃用NSSecureCoding,因此您应该使用该一致性以避免将来的支持问题。

class Device : NSObject, NSSecureCoding {

    static var supportsSecureCoding: Bool = true

    var deviceId : Int?
    var driver : String?
    var address : String?
    var type : DeviceTypes? // Enum type

    func encode(with coder: NSCoder) {
        coder.encode(self.deviceId, forKey: "deviceId")
        coder.encode(self.driver, forKey: "driver")
        coder.encode(self.address, forKey: "address")

        coder.encode(self.type?.rawValue, forKey: "type")
    }

    required init?(coder: NSCoder) {
        super.init()

        self.deviceId = coder.decodeInteger(forKey: "deviceId")
        self.driver = coder.decodeObject(forKey: "driver") as? String
        self.address = coder.decodeObject(forKey: "address") as? String

        let rawtype = coder.decodeInteger(forKey: "type")
        self.type = DeviceTypes(rawValue: rawtype)
    }

}

您尚未在Device类中提供所有代码,因为您的帖子片段未按Codable一致性进行编译,所以我无法猜测您的系统在JSON支持方面真正需要什么。

© www.soinside.com 2019 - 2024. All rights reserved.