Chapter 16, loading data saved

As the book requests I added this:

In Xcode 8.3.3

init() {
if let archivedItems = NSKeyedUnarchiver.unarchiveObject(withFile: itemArchiveURL.path) as? [Item] {
allItems = archivedItems
}
}

When I run it I get this:

omepwner[75541:7135722] *** Terminating app due to uncaught exception ‘NSInvalidUnarchiveOperationException’, reason: ‘*** -[NSKeyedUnarchiver decodeInt64ForKey:]: value for key (name) is not an integer number’

Here is my code that seemed to work for storing values into [Item]:

required init(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: “name”) as! String
dateCreated = aDecoder.decodeObject(forKey: “dateCreated”) as! Date
itemKey = aDecoder.decodeObject(forKey: “itemKey”) as! String
serialNumber = aDecoder.decodeObject(forKey: “serialNumber”) as! String

valueInDollars = aDecoder.decodeInteger(forKey: "name")

super.init()

}

Xcode 8.3.3 adds a caution note to:
serialNumber = aDecoder.decodeObject(forKey: “serialNumber”) as! String
it would prefer it to read:
serialNumber = (aDecoder.decodeObject(forKey: “serialNumber”) as! String)
but I didn’t do this.

Suggestions?

The following line of code looks suspicious:

valueInDollars = aDecoder.decodeInteger (forKey: "name")

Check the object stored behind the key named name. Is the object’s value type integer?

YES! Success, but your suggestion allowed me to notice the bigger problem –

1st: the statement should read -
valueInDollars = aDecoder.decodeInteger (forKey: “valueInDollars”)

Its previous value was “name” This means two items stored had the same key “name”.
Later the decode pulled up the item with a string and tried to decode it as an integer.
The trap resulted.