When I run the following code:
let saveAction = UIAlertAction(title: "Save",
style: .default) {
[unowned self] action in
guard let textField = alert.textFields?.first,
let mapName = textField.text else {
return
}
var newCoordinate = NSEntityDescription.insertNewObject(forEntityName: "Coordinates", into: managedObjectContext)
var newMap = NSEntityDescription.insertNewObject(forEntityName: "MapNames", into: managedObjectContext)
newCoordinate.setValue(23, forKey: "latitude")
newCoordinate.setValue(21, forKey: "longitude")
newMap.setValue(mapName, forKey: "mapname")
do
{
try self.appDelegate.saveContext()
print("SAVED")
}
catch
{
}
var request = NSFetchRequest<NSFetchRequestResult>(entityName: "Coordinates")
request.returnsObjectsAsFaults = false
do
{
var results = try managedObjectContext.fetch(request)
if results.count > 0 {
for result in results as! [NSManagedObject]
{
if let latitude = result.value(forKey: "latitude") as? Double
{
print(latitude)
}
if let longitude = result.value(forKey: "longitude") as? Double{
print(longitude)}
if let map = result.value(forKey: "mapname") as? String {
print(map)}
}
}
}
catch
{
}
I get the following error:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: the entity Coordinates is not key value coding-compliant for the key "mapname".'
This is weird because I do have an attribute called mapname, although it is in the MapNames entity. The error says Coordinates, why is that?
Is that because it is not possible to have 2 references to managedObjectContext in the same scope? How could I insert values to different entities then?
You can fix the error by breaking the connection that is causing the problem. Simply click the X to delete the outlet. Then you can go back to the View Controller and simply recreate the connection. Just hold the control key and drag and drop the mouse pointer to the outlet you want to connect.
About Key-Value Coding. Key-value coding is a mechanism enabled by the NSKeyValueCoding informal protocol that objects adopt to provide indirect access to their properties. When an object is key-value coding compliant, its properties are addressable via string parameters through a concise, uniform messaging interface.
I got this same error after upgrading to Swift 4.
I had to add @objcMembers to my Entity class (or @objc to each property of the class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With