The Class is not key value coding compliant?

I have a macOS app that contains a tableView. The tableView has 7 columns and is populated from a SQLite table. The tableView displays data for 6 of the 7 columns. On the last column I get the following error:valueForUndefinedKey:]: this class is not key value coding-compliant for the key itemUsedLast. The problem was in the following code:
Code Block
    func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
        let identifier = tableColumn?.identifier
        //   print(#function,identifier, items[row], identifier?.rawValue)
        let str = items[row].value(forKey: identifier!.rawValue)
        //  let str = items[row].identifier!)
        return str
    }

When I comment out this code it works fine. Any thoughts on how to debug further?
Answered by Claude31 in 646746022
The crash comes most likely from a wrong key. The column identifier does not match the property name.

Make this test, in playground

I tested the following in playground. It works. And of course crashes if you replace
Code Block
forKey: "itemLastused"
// for instance by
forKey: "ItemLastused"


Code Block
class Item: NSObject {
@objc var itemNumber: String? = ""
@objc var itemLastused: Date?
}
var items:[Item] = []
let item = Item()
item.itemNumber = "100"
item.itemLastused = Date()
items.append(item)
let valueForNumberKey = items[0].value(forKey: "itemNumber")
let valueForDateKey = items[0].value(forKey: "itemLastused")

So, the key must be the exact same name as the property declaration.
Accepted Answer
The crash comes most likely from a wrong key. The column identifier does not match the property name.

Make this test, in playground

I tested the following in playground. It works. And of course crashes if you replace
Code Block
forKey: "itemLastused"
// for instance by
forKey: "ItemLastused"


Code Block
class Item: NSObject {
@objc var itemNumber: String? = ""
@objc var itemLastused: Date?
}
var items:[Item] = []
let item = Item()
item.itemNumber = "100"
item.itemLastused = Date()
items.append(item)
let valueForNumberKey = items[0].value(forKey: "itemNumber")
let valueForDateKey = items[0].value(forKey: "itemLastused")

So, the key must be the exact same name as the property declaration.
You are correct. I had a name mismatched and once I changed this in now works fine!
The Class is not key value coding compliant?
 
 
Q