我正在从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对其进行存档时,它会抛出Exception:

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

设备类型
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
}

最佳答案

您的问题是NSCoding仅适用于类类型。尝试使DeviceTypesNSCoding一致将导致错误

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支持方面真正需要什么。

关于ios - 无法使用NSKeyedArchiver保存我的模型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61886300/

10-12 06:23