KVC not working as described in chapter 8 and 9 (XCode 10.1)

I’v just upgraded to XCode 10.1.
On page 135, when trying to execute

s.setValue( "Kelly", forKey: "name")

I get the error message

error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

Same issue in chapter 9: When running the app as at page 165 I get the following error at startup:

2018-12-28 08:11:14.328656+0100 RaiseMan[5201:152745] [<RaiseMan.Document 0x600002918380> valueForUndefinedKey:]: this class is not key value coding-compliant for the key employees.

There seems to be change in the KVC-mechanism and I’m lost.

Remember this book was written for Swift 1, I believe. They apparently have no intentions of updating it. BNRs git page has updated code to Swift 2.0, helpful, but still way out of date.

You now have to add ‘@objc dynamic’ preceding the property declarations for KVC to work (KVC/KVO is Objective-C and to expose Swift to Objective-C you have to add that code). This was done in a previous Swift version.

class Student: NSObject {
    @objc dynamic var name = ""
    @objc dynamic var gradeLevel = 0
}

and:

class Employee: NSObject, NSCoding {
    @objc dynamic var name: String? = NSLocalizedString("DEFAULT_NAME", comment: "The default name displyed")
    @objc dynamic var raise: Float = 0.05

    ...

}

Note: this RaiseMan, Employee code might not be just like yours, I copied it from mine, and I’ve finished the book. Some features, like localization, might not have been discussed yet. I don’t remember what chapter that was in. But the @objc dynamic is the same as what you need now.

3 Likes