In core data I have set my entities to Category/Extension mode.
In my xdatamodel view I have created some properties and relationships.
I tried to add another property to one of my generated entity file but I can't seem to access this property when I create a new object.
Here is my example:
I know that Core Data generates a String property for my object, let's call it a car object like so.
import Foundation
import CoreData
Extension Car {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Sellable>
@NSManaged public var name: String?
}
Very simple right? I do not create that file but I know this is what CoreData auto-generates.
Now when I try to write my "Car+CoreDataClass.swift" to add a property like this here below:
import Foundation
import CoreData
@objc(Car)
public class Car: SomeParentClassThatInheritsFromNSManagedObject {
@NSManaged var nameTest: String?
}
I cannot set my instance's property value with someCarInstance.setValue("End of Line buddy!", forKey: "nameTest")
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: the entity Car is not key value coding-compliant for the key "nameTest".'
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Car setNameTest:]: unrecognized selector sent to instance 0x6080000aeb20' (note here, I create an NSManagedObject and have to cast is to a Car entity to get the object oriented functions and naming convention. So CoreData does see it but its not managing it.
Is this something that should never be done and why? Originally, I tried to create this property in my parent(super) class but like you see, I tested this directly in the class itself and I get the same errors. Is this something CoreData is not supposed to look in my Car class file for @NSManaged properties? In my mind that should have worked.
If you have an @NSManaged
property, that property must be declared in the managed object model.
With @NSManaged
you're saying that this property will be managed by Core Data. Core Data can't do that unless it knows about the property. It doesn't know about the property unless it's in the managed object model.
If you want this to be managed by Core Data, you need to add it to the data model.
If you don't want this to be managed by Core Data, get rid of the @NSManaged
.
But-- as you are finding-- you can't just declare that it's @NSManaged
unless you include it in the data model.