I created a CoreData Model with an Entity "News" :
I set it to "Manuel/None" and created a NSManagedObject :
public class News: NSManagedObject {
@NSManaged var id: String
@NSManaged var newsType: Int16
@NSManaged var newsImageUrl: String
@NSManaged var newsVideoUrl: String
@NSManaged var newsTitle: String
@NSManaged var newsDesc: String
}
I want to override the properties of my entity without touching the CoreData Model, just by doing this :
extension News {
@NSManaged var newsUrl: String
}
Of course, if I do :
news.newsUrl = ""
I get a nice
reason: '-[NSManagedObject setNewsUrl:]: unrecognized selector
How can I add properly new properties in my Entity (without modifying CoreData Model) and, of course, I want this news property to be saved in CoreData ?
TY
The approach you tried doesn't work because it's not enough to just declare the new property, you have to make that property exist in the data model. If you don't edit the model, you have to do the work in your code.
You can modify the entire model in code until you start using it. Once you load your persistent store file, you have to treat the object model as read-only. The basic steps would be
NSManagedObjectModel
for its entities
or entitiesByName
.NSEntityDescription
in that list.NSAttributeDescription
for your new property.properties
array on the entity.This is not a good idea, and I strongly recommend not doing it, but it's not impossible. In many years of Core Data coding I've only modified the model in code once, to work around a (since fixed) bug in the model compiler.
Keep in mind that this does not let you avoid doing model migration. Your persistent store file must match the data model that you use. Modifying the model in code will make managing model versions more difficult, and will increase the odds of the app crashing because the models don't match.