Swift: nscoding decodeObject with zero all the time

I received the following codes for recording an object named Packet and sending it to the other side through a Multipeer connection. However, when I tried to decode the encoded object, I received the following error.

  class Packet : NSObject, NSCoding {

  var tmp1: Double = 0
  var tmp2: Double = 0

  struct PropertyKey {
    static let tmp1Key = "tmp1Key"
    static let tmp2Key = "tmp2Key"
  }


  init(tmp1: Double, tmp2: Double) {
    self.tmp1 = tmp1
    self.tmp2 = tmp2
    super.init()
  }

  deinit {
  }

  required convenience init(coder aDecoder: NSCoder) {
    debugPrint("initcoder")
    let tmp1 = aDecoder.decodeObject(forKey: PropertyKey.tmp1Key) as! Double // crash here
    let tmp2 = aDecoder.decodeObject(forKey: PropertyKey.tmp2Key) as! Double
    self.init(tmp1: tmp1, tmp2: tmp2)
  }

  public func encode(with aCoder: NSCoder) {
    debugPrint("encodeCoder")
    aCoder.encode(tmp1, forKey: PropertyKey.tmp1Key)
    aCoder.encode(tmp2, forKey: PropertyKey.tmp2Key)
  }
}

The error I received ---- Printing with me ---- "initcoder" fatal error: nil unexpectedly found while deploying an optional value 2016-09-30 13: 32: 55.901189 Communication [323: 33022] fatal error: unexpectedly detected zero when deploying an optional value

But when I create the object, all values ​​are set. I infected the package object without any problems.

---- Additional Information ------ I used the following codes to encode and decode data when sending to the other side through the possibility of animation.

 func dataForPacket(packet: Packet) -> Data {
    let data = NSMutableData()
    let archiver = NSKeyedArchiver(forWritingWith: data)
    archiver.encode(packet, forKey: "Packet")
    archiver.finishEncoding()
    debugPrint("dataForPacket \(data) \(packet)")
    return data as Data
  }

  func packetForData(_ data: Data) -> Packet {
    debugPrint("packetForData")
    let unarchiver = NSKeyedUnarchiver(forReadingWith: data)

    let packet: Packet = unarchiver.decodeObject(forKey: "Packet") as! Packet 
     // crash here (as this will call the init of the Packet class)
    debugPrint("packetForData \(packet)")
    return packet
  }

, . .

+10
3

Swift 3:

. decoder.containsValue, , .

decodeDouble (forKey:). decodeObject (forKey:)

 var dateTime: TimeInterval = SOME_TIME_INTERVAL (Double)//Can be saved(encoded) previously, and not encoded as well.
 aCoder.encode(dateTime, forKey: "dateTime")
 if decoder.containsValue(forKey: "dateTime") {
            dateTime = decoder.decodeDouble(forKey: "dateTime")
        }
+12

, Double Bool, decodeDouble:forKey decodeBool:forKey , nil.

+1

Swift 4.2:

decodeObject(forKey:) nil. encode(_:forKey:) Int NSNumber, .

decodeInteger(forKey:)reads it as an int and returns it. decodeInteger(forKey:)you can use decodeInteger(forKey:), Int(decodeInt32(forKey:))or Int(decodeInt64(forKey:)).

+1
source

Source: https://habr.com/ru/post/1656306/


All Articles