I am getting model from Api and it looks like this:
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
}
}
Then I am adding some elements to array and it works but when I am trying to archive it with NSKeyedArchiver it throws an Exception :
[__SwiftValue encodeWithCoder:]: unrecognized selector sent to instance
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
}
Your problem is
NSCodingis only available for class types. Any attempt to conformDeviceTypestoNSCodingwill result in an errorOne solution is to convert back and forth from the
enumtype in yourNSCodingmethods.Note that
NSCodingis soft deprecated forNSSecureCodingso you should use that conformance to avoid future support issues.You haven't supplied all the code in your
Deviceclass as your post fragment doesn't compile withCodableconformance so I can't guess at what your system really requires in terms of JSON support.