I am having problem with encoding/decoding with KeyedArchiver in Swift 3. I managed to reproduce the problem with this small class for which an instance can be encoded with a key but does not seem to be decoded with the same key.
Any suggestion or hint will be appreciated...
Here is the full code and the stack trace when it fails in decoding
----
import Foundation
class MyClass : NSObject, NSCoding {
var a : Int
init(a:Int) {
self.a = a
}
required init(coder aDecoder: NSCoder) {
self.a = aDecoder.decodeObject(forKey: "a") as! Int
}
func encode(with aCoder: NSCoder) {
aCoder.encode(a, forKey: "a")
}
override var description: String {
return "\(a)"
}
}
let m1=MyClass(a: 8)
print("m1=\(m1)")
let archivedClass=NSKeyedArchiver.archivedData(withRootObject: m1)
print("archivedClass=\(archivedClass)")
let deArchivedClass=NSKeyedUnarchiver.unarchiveObject(with: archivedClass)
print("deArchivedClass=\(deArchivedClass as AnyObject)")
/* output after stopping at self.a = aDecoder.decodeObject(forKey: "a") as! Int
m1=8
archivedClass=250 bytes
fatal error: unexpectedly found nil while unwrapping an Optional value
Current stack trace:
0 TestEncoding 0x000000010031bfe0 swift_reportError + 132
1 TestEncoding 0x0000000100339390 _swift_stdlib_reportFatalError + 61
2 TestEncoding 0x0000000100002fd0 specialized specialized StaticString.withUTF8Buffer<A> ((UnsafeBufferPointer<UInt8>) -> A) -> A + 656
3 TestEncoding 0x00000001002a93c0 partial apply for (_fatalErrorMessage(StaticString, StaticString, StaticString, UInt, flags : UInt32) -> Never).(closure #2) + 109
4 TestEncoding 0x0000000100002fd0 specialized specialized StaticString.withUTF8Buffer<A> ((UnsafeBufferPointer<UInt8>) -> A) -> A + 656
5 TestEncoding 0x0000000100263d80 specialized _fatalErrorMessage(StaticString, StaticString, StaticString, UInt, flags : UInt32) -> Never + 96
6 TestEncoding 0x00000001000027a0 MyClass.init(coder : NSCoder) -> MyClass + 329
7 TestEncoding 0x0000000100002a20 @objc MyClass.init(coder : NSCoder) -> MyClass + 45
8 Foundation 0x00007fff8ec2e9ac _decodeObjectBinary + 2743
9 Foundation 0x00007fff8ec2e78c _decodeObject + 281
10 Foundation 0x00007fff8ec2d7ba +[NSKeyedUnarchiver unarchiveObjectWithData:] + 89
11 TestEncoding 0x0000000100001ca0 main + 1172
12 libdyld.dylib 0x00007fff8e5625ac start + 1
*/