Swift NSCoding how to decode custom object

92 Views Asked by At

I've a dictionary ("equippedItems") of custom objects that I'd like to encode and decode.

var equippedItems = [ItemType : ItemEntity]() 

I've tried to encode it as following:

override func encode(with aCoder: NSCoder) {
    aCoder.encode(equippedItems, forKey: "Equiptments")
}

but it causes the app to crash. Therefore I tried to use the following code to encode it and app no longer crashes. Is that the right way?

override func encode(with aCoder: NSCoder) {
        let eq = try? NSKeyedArchiver.archivedData(withRootObject: equippedItems, requiringSecureCoding: false)
        aCoder.encode(eq, forKey: "Equiptments")
}

However, now I'm having trouble decoding the object in the following function:

required convenience init?(coder aDecoder: NSCoder) {
    equippedItems = aDecoder.decodeObject(forKey: "Equiptments") as! [ItemType: ItemEntity]
}

The app crashes with an error:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Although I don't get an error from the encoding lines, I'm still not sure if it was the correct way to encode it.

Can someone please show me how I encode and decode it properly?

1

There are 1 best solutions below

5
Duncan C On

In order to use NSCoding you have to make every object in your object graph conform to NSCoding. Where is your NSCoding conformance for ItemType and ItemEntity?