twilight2 twilight2 - 1 month ago 7
iOS Question

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSEntityDescription 0x7fc863f27230> setValue:forUndefinedKey:]

i try to learn core data it is fully basic . unfortunately this error throwing


Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key title.


so by this time app terminate.


terminating with uncaught exception of type NSException


what should i do ? what am i missing thanks

Here is the code in viewcontroller

@IBAction func createMangeObjectBtn(sender: AnyObject) {

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

let context = appDelegate.managedObjectContext

let entityForName = NSEntityDescription.entityForName("Book", inManagedObjectContext: context)

entityForName?.setValue("iOS Programming", forKey: "title")
entityForName?.setValue("12/12/12", forKey: "publishDate")
entityForName?.setValue("NH001", forKey: "code")
entityForName?.setValue("tolight", forKey: "author")


do{
try context.save()
print("saved")
}
catch{
print("something happend")
}

}


Here is the model:
enter image description here

Answer

Your code

let entityForName =  NSEntityDescription.entityForName("Book", inManagedObjectContext: context)

creates a NSEntityDescription and not an object of that entity.

What you want is

let book = NSEntityDescription.insertNewObjectForEntityForName("Book", inManagedObjectContext: context)
book.setValue("iOS Programming", forKey: "title")
// ...

Or better, create a NSManagedObject subclass for the entity and use the property accessors directly:

let book = NSEntityDescription.insertNewObjectForEntityForName("Book", inManagedObjectContext: context)
book.title = "iOS Programming"
// ...