NSKeyedUnarchiver EXC_BAD_INSTRUCTION 与协议

NSKeyedUnarchiver EXC_BAD_INSTRUCTION with protocol

我正在更新我的应用程序以支持 IOS 11 个版本 目前它适用于 IOS 13.2 但是在 IOS 11 和 IOS 12.2 我有 EXC_BAD_INSTRUCTION 在 NSKeyedUnarchiver decodeObject

有错误的class

class Seance : NSObject, NSCoding{
  var date: NSDate
  var action: [String:ObjectifData] = Seance.actionStartupPoint()
  var duration = 0.0
  static var instance: Seance? = nil

static func actionStartupPoint() -> [String: ObjectifData]{
    var a: [String: ObjectifData] = [String:ObjectifData]()
    for objectif in Storage.instance.objectif{
        a[objectif.key] = objectif.value.type.initialise
    }
    return a;
}


init(date: NSDate){
    self.date = date;
}

required init(coder decoder: NSCoder){
    self.date = decoder.decodeObject(forKey: "date") as! NSDate
    self.action = try decoder.decodeObject(forKey: "action") as! [String: ObjectifData] // EXC_BAD_INSTRUCTION ERROR
    self.duration = decoder.decodeDouble(forKey: "duration")
}
func encode(with coder: NSCoder){
    print(action)
            print(date)
                    print(duration)
    coder.encode(date, forKey: "date")
    coder.encode(action, forKey: "action")
    coder.encode(duration, forKey: "duration")
}

func convertActionToObjectifData() -> [String: Objectif]{
    var dic: [String: Objectif] = [:]
    for convert in action{
        if Storage.instance.objectif[convert.key] != nil {
            dic[convert.key] = Storage.instance.objectif[convert.key]!
        }
    }
    return dic
}
}

ObjectifData 是具有 3 个父节点的协议

像这样

class BinaireData : NSObject, NSCoding, ObjectifData {

var validate: Bool = false

func encode(with coder: NSCoder) {
    coder.encode(validate, forKey: "validate")
}
override init(){}
required init(coder decoder: NSCoder) {
    super.init()
    self.validate = decoder.decodeBool(forKey: "validate")
}


func getObjectifType() -> ObjectifType {
    return .binaire
}

func getPrimaryValue() -> Double {
    return validate ? 1 : 0
}

func stringFormatedValue() -> String {
    return validate ? "Oui" : "Non"
}
func updateFromWatch(message: [String : Any]) -> Bool {
    let value: Bool = message["event"] as! Bool
    if(self.validate != value){
        self.validate = value
        return true
    }
    return false
}
}

ObjectifData =

protocol ObjectifData: NSObject {

func getObjectifType() -> ObjectifType
func getPrimaryValue() -> Double
func stringFormatedValue() -> String
func updateFromWatch(message: [String:Any]) -> Bool}

为了加载这个,我在启动时这样做

training = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as! [String: [Seance]]

Breakpoint Stack trace

经过多次研究,我注意到问题的发生可能是由于 ios11

上的 NSKeyUnarchiver 中不允许使用的协议

是真的吗? 我该如何解决这个问题? 谢谢阅读 祝你有美好的一天

为了能够对采用 ObjectifData 的 类 进行编码,它还必须被限制为 NSCoding

protocol ObjectifData: NSObject, NSCoding

您正在尝试对类型为 [String: ObjectifData] 的对象进行编码和解码,其中 ObjectifData 是一种协议。你不能那样做;协议不是真正的类型!我对崩溃并不感到惊讶;我很惊讶这也不会在 iOS 13 中崩溃。