1

I'm following a tutorial on KVC and KVO when I attempted to enter the code into a playground however it wouldn't run. I received the error "terminating with uncaught exception of type NSException". I even tried to create a single app application and entered the information into a viewController to see what happens and it still wouldn't build which provided the error that the object wasn't key coding compliant. I'd really like to see this work, what am I doing incorrectly?

import UIKit
import Foundation


//this is a reference object which means when it is copied, it will copy a reference to the same instance and not a brand new value like a value type does
class Student: NSObject {
    var name: String = ""
    var gradeLevel: Int = 0
}


let seat1 = Student()
seat1.setValue("Kelly", forKey: "name")
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Laurence Wingo
  • 3,912
  • 7
  • 33
  • 61
  • 1
    Your issue has nothing to do with using a playground. You get the error no matter where you run it: *"'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name.'"* – rmaddy May 18 '18 at 01:54

1 Answers1

2

Your issue is not the playground. Your issue is that to use the Objective-C KVC mechanism, you need to mark the property with @objc.

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

Adding that will fix the crash.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • I thought subclassing from NSObject would handle interfacing with the Objective-C runtime? Is that not the case or has it ever been the case? – Laurence Wingo May 18 '18 at 02:18
  • Thank you so much! I was reading <2015 - Cocoa Programming for OS X 5th> and got this problem too. – NamNamNam Aug 06 '20 at 10:50